【发布时间】:2018-03-22 13:41:01
【问题描述】:
我在 UITextView 中集成的应用程序中有以下文本
使用此应用,即表示您同意我们的用户协议和隐私政策。
我想要实现的是为将打开 SafariViewController 的两个粗体部分识别单独的点击。我需要的是链接识别之类的东西,我可以在其中放置文本
使用此应用程序即表示您同意我们的用户协议(链接:@“https://google.com/agreement”)和隐私政策(链接:@“https://google.com/privacy” )。
我希望此文本显示为上述文本,并在单击 textView 时打开这些“隐藏”链接。这可能吗?我找到了一个解决方案,其中一个人创建了 N 个 UILabel(每个标签是 1 个字符),在带下划线的文本上附加手势识别器。我讨厌这个解决方案,因为当 iOS 已经为您提供了支持链接文本的 TextView 时,它更像是一种 hack,而不是一种解决方案。
编辑:
在以下几个建议和一些调整后找到了一个可行的解决方案...
您需要创建 UITextView,您将在其中创建链接文本
-
为普通文本和标记为链接的文本创建文本属性
NSDictionary *orangeTextAttributes = @{NSForegroundColorAttributeName: [UIColor orangeColor], NSFontAttributeName: [UIFont systemFontOfSize:14 weight:UIFontWeightThin], NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)}; NSDictionary *normalTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor], NSFontAttributeName: [UIFont systemFontOfSize:14 weight:UIFontWeightThin]}; -
对文本使用该属性
NSMutableAttributedString *labelAttributedText = [[NSMutableAttributedString alloc] initWithString:@"By using this application, you agree to Google's User Agreement and Privacy Policy." attributes:normalTextAttributes]; [self addLink:@"https://google.com/terms-of-services" toString:@"User Agreement" ofAttributedString:labelAttributedText]; [self addLink:@"https://google.com/privacy" toString:@"Privacy Policy" ofAttributedString:labelAttributedText]; self.termsAndPolicyTextView.linkTextAttributes = orangeTextAttributes; self.termsAndPolicyTextView.attributedText = labelAttributedText; -
添加方法以将链接附加到您的 TextView 文本
- (void)addLink:(NSString *)urlString toString:(NSString *)substringToBeLinked ofAttributedString:(NSMutableAttributedString *)entireAttributedString { NSRange substringRange = [[entireAttributedString string] rangeOfString:substringToBeLinked]; if (substringRange.location != NSNotFound) { [entireAttributedString addAttribute:NSLinkAttributeName value:urlString range:substringRange]; } } -
攻击委托到您的文本视图,并处理注册链接点击的回调
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction { //This is where you open your link in browser for example return NO; }
【问题讨论】:
-
使用
NSAttributedString和对应的UITextViewDelegate来处理链接上的触摸。 -
我没有链接,我只有文字。需要验证触摸的位置是否在“所需字符串”的范围内。
-
这正是
NSAttributedString所做的。参考stackoverflow.com/questions/21629784/… -
另一个链接(没有双关语)可以帮助检测对某个单词的点击:stackoverflow.com/questions/11349459/…
-
"User Agreement(link:@"google.com/agreement") " 这就是正确设置 NSAttributedString 的方法。它将在“用户协议”下嵌入链接,将其转换为“可点击的单词”换句话说...
标签: ios uitextview