Add UITapGestureRecognizer to NSAttributed Text wi

2019-07-31 22:51发布

I have an attributed string set up like this:

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

and i would like to add a tap gesture just to the range that i set to green.

Is there an attribute for touches? How would i set the tap gesture just for the spellingStr part?

EDIT

all my code for that label and string is below:

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条回答
趁早两清
2楼-- · 2019-07-31 23:37

I've done it by just creating a UIButton and setting it to the exact frame of that line of text.

Here's an example of how to do it in 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];

NOTE: prior to calling this, you should have already setup your attributed string and added it to your UITextView. Also, ensure you allow selection inside your textView (but disable userInteraction if you dont want highlights etc)

enter image description here

查看更多
登录 后发表回答