将click事件添加到ios NSString中的某些文本 [英] Add a click event to some text in ios NSString
问题描述
我有以下代码,并且想让我的文本部分可以点击并调用另一个UIViewController(而不是网站)。
I have the following code and want to make parts of my text be clickable and call another UIViewController (not a website).
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"testing it out @clickhere"];
NSInteger length = str.length;
[str addAttribute:NSForegroundColorAttributeName value:[UIColor bestTextColor] range:NSMakeRange(0,length)];
NSMutableAttributedString设置为UILabel,如下所示:
The NSMutableAttributedString gets set to a UILabel like so:
label.attributedText = str;
最好的方法是什么?我似乎无法找到一个好的答案。
Whats the best way to do this? I can't seem to find a great answer.
我想要的一个例子是假设我有一个UILabel,如下所示:
An example of what I want is suppose I have a UILabel like so with the following text:
This is my label. Click here to go to UIViewController1 and then go to UIViewController1 by this #tag.
我希望第一次点击事件和单词#tag传递here文本要传递给相同的点击事件。
I want the text "here" to be passed for the first click event and the word "#tag" to be passed to the same click event.
推荐答案
如果您使用值字段传入目的地该怎么办?
What if you used the value field to pass in the destination?
[attributedString addAttribute:NSLinkAttributeName
value:[@"destinationController1" stringByAppendingString:username]
range:range];
然后覆盖委托方法:
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
if ([URL.scheme isEqualToString:@"destinationController1"]) {
// Launch View controller
return NO;
}
return YES;
}
这篇关于将click事件添加到ios NSString中的某些文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!