将UITapGestureRecognizer添加到带有范围的NSAttributed Text

时间:2014-11-20 14:14:49

标签: ios objective-c swift ios8

我有一个像这样设置的属性字符串:

var range = (showStr as NSString).rangeOfString(spellingStr)
var attributedString = NSMutableAttributedString(string:showStr)
attributedString.addAttribute(NSForegroundColorAttributeName, value: ezGreen, range: range)

我想在我设置为绿色的范围内添加一个轻击手势。

是否有触摸属性?如何为spellingStr部分设置点击手势?

修改

该标签和字符串的所有代码如下:

var showStr:NSString = "Showing results for \(searchT)."
println("SearchTerm:\(searchT)")
showingLabel.textColor = .blackColor()

var range = (showStr as NSString).rangeOfString(searchT)
var attributedString = NSMutableAttributedString(string:showStr)
attributedString.addAttribute(NSForegroundColorAttributeName, value: ezGreen , range: range)

showingLabel.attributedText = attributedString
showingLabel.font = UIFont.systemFontOfSize(17)
showingLabel.numberOfLines = 0
showingLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
var showHeight:CGFloat = heightForView(showingLabel.text!, UIFont.systemFontOfSize(17), maxLabelWidth)
showingLabel.frame = CGRectMake(20, heightOfCor, maxLabelWidth, showHeight)
heightOfCor += showHeight
bgBlack.addSubview(showingLabel)

1 个答案:

答案 0 :(得分:4)

我是通过创建一个UIButton并将其设置为该行文本的确切框架来完成的。

以下是如何在objective-c中执行此操作的示例:

NSRange range = [self.textView.text rangeOfString:@"The string of text you want to tap"];
self.textView.selectedRange = range;
UITextRange *textRange = [self.textView selectedTextRange];
CGRect textRect = [self.textView firstRectForRange:textRange];
CGRect convertedRect = [self.view convertRect:textRect fromView:self.textView];

UIButton *button = [[UIButton alloc]initWithFrame:convertedRect];
[button setBackgroundColor:[UIColor clearColor]];
[button addTarget:self action:@selector(textTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[self.view bringSubviewToFront:button];

注意:在调用此函数之前,您应该已经设置了属性字符串并将其添加到UITextView中。此外,确保您允许在textView中进行选择(但如果您不想要高亮显示等,则禁用userInteraction)

enter image description here