【发布时间】:2017-07-13 03:53:19
【问题描述】:
我当前的 URL 长度为 801 个字符。我发现如果 URL 长度超过 350 个字符,则自动检测链接在 UITextView 中不起作用。此外,我在“消息”应用程序中测试了我的链接,它不起作用(消息将使用 UILabel 或 UITextView 来显示文本内容)。有什么方法可以检测到长度超过 350 个字符的 URL?
【问题讨论】:
标签: ios url hyperlink uilabel uitextview
我当前的 URL 长度为 801 个字符。我发现如果 URL 长度超过 350 个字符,则自动检测链接在 UITextView 中不起作用。此外,我在“消息”应用程序中测试了我的链接,它不起作用(消息将使用 UILabel 或 UITextView 来显示文本内容)。有什么方法可以检测到长度超过 350 个字符的 URL?
【问题讨论】:
标签: ios url hyperlink uilabel uitextview
如果 UITextView 的数据检测器在您的调查中无法检测到长度超过 350 个字符的 URL,我认为您可以自己使用正则表达式来做到这一点。检测到 URL 后,可以使用 attributesString 设置为 UITextView。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
self.textView.textColor = [UIColor blackColor];
self.textView.contentInset = UIEdgeInsetsMake(0, 0, 10, 0);
NSString *testString = @"google dog meme https://www.google.com.sg/search?q=dog+meme&espv=2&biw=1672&bih=890&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjWr8rexqXSAhUO9GMKHYHXD7QQ_AUIBigB#tbm=isch&q=doge+meme&imgrc=SFF-4BKQucOc4M: hhahaa";
NSDataDetector *detect = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [detect matchesInString:testString options:0 range:NSMakeRange(0, [testString length])];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:testString attributes:nil];
NSTextCheckingResult *result = matches.firstObject;
if (result) {
[attributedString addAttribute:NSLinkAttributeName value:result.URL.absoluteString range:result.range];
}
self.textView.editable = NO;
self.textView.attributedText = attributedString;
self.textView.userInteractionEnabled = YES;
self.textView.delegate = self;
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
NSLog(@"#### %@", URL);
return YES;
}
另一种方法是先使用 URL 缩短器来缩短您的 URL,然后再显示它们。我认为这在用户体验方面很有价值,因为用户可能不愿意点击很长的 URL。
希望对你有帮助。
【讨论】:
URL length 1332 测试过,它工作正常。我可以突出显示 URL,它是可点击的。你设置self.textView.editable = NO;了吗?