问题描述
任何人都知道如何在IOS7中的评论文本中使#KEY和@NAME可以点击(例如,与Instagram相同的方式)?我正在尝试使用NSMutableAttributedString,但我不确定如何检测点击事件,在下图中点击@Username应该将用户带到用户的个人资料
Anyone knows how I can make the #KEY and @NAME clickable in the text of comments in IOS7 (the same way that instagram does it for example)? i am trying to use NSMutableAttributedString but I'm not sure how to detect click event, in the image below clicking @Username should take the user to the profile of the user
推荐答案
查看,iOS7中有一个新方法: textView: shouldInteractWithURL:inRange:
。
Looking at the UITextViewDelegate
protocol, there is a new method in iOS7: textView:shouldInteractWithURL:inRange:
.
您没有共享任何代码,但可以安全地假设您有一个 attributionString
和范围
表示您变成蓝色的区域。我还假设您可以将用户名提取到名为 username
的变量中。
You didn't share any code, but it is safe to assume you have an attributedString
and a range
representing the area you turned blue. I'll also assume you can extract the username into a variable called username
.
这三条信息,你将链接属性添加到该范围。
With these three pieces of information, you add a link attribute to that range.
[attributedString addAttribute:NSLinkAttributeName
value:[@"username://" stringByAppendingString:username]
range:range];
在你的代表中,你可以这样做:
In your delegate, you could do something like this:
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
if ([URL.scheme isEqualToString:@"username"]) {
[self doSomethingWithUserName:URL.host];
return NO;
}
return YES;
}
我相信他们在WWDC 2013的介绍文本工具包会议中进行了演示。
I believe they demoed this in the Introducing Text Kit session at WWDC 2013.
这篇关于如何在IOS7中使#key和@key可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!