在iOS 7应用程序中,我有一个UITextView
链接,但点击链接不会触发.它只响应尴尬的"轻拍".我希望它在用户点击它时立即响应,就像UIWebView
链接点击工作方式一样.这是我的设置:
- (void)viewDidLoad { [super viewDidLoad]; NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."]; [text addAttribute:NSLinkAttributeName value:@"myurl://tapped" range:NSMakeRange(6, 16)]; self.textView.attributedText = text; self.textView.editable = NO; self.textView.delaysContentTouches = NO; } - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { if ([[URL scheme] isEqualToString:@"myurl"]) { // Handle tap return NO; } return YES; }
该shouldInteractWithURL
方法的Apple文档说明:"如果用户点击或长按URL链接,文本视图将调用此方法".长按工作正常,但水龙头似乎不起作用.
有谁知道怎么让这个立即回应?
如果您仍想使用本机UITextView
,可以在文本视图中添加点按识别器,并在点按位置获取字符串属性.找到链接后,您可以立即打开它.
我写了一个Gist解决了iOS 7/8的问题.这是一个轻量级的扩展UITextView
,也转发-[UITextViewDelegate textView:shouldInteractWithURL:inRange:]
和暴露内部点击手势识别器.
https://gist.github.com/benjaminbojko/c92ac19fe4db3302bd28
这是一个简单的示例:下面的示例仅适用于iOS 8.请参阅上面的要点以获得iOS 7 + 8支持.
添加点击识别器:
// ... UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedTextView:)]; [myTextView addGestureRecognizer:tapRecognizer]; myTextView.selectable = YES; // otherwise the gesture won't recognize // ...
并添加您的回调:
- (void)tappedTextView:(UITapGestureRecognizer *)tapGesture { if (tapGesture.state != UIGestureRecognizerStateEnded) { return; } UITextView *textView = (UITextView *)tapGesture.view; CGPoint tapLocation = [tapGesture locationInView:textView]; UITextPosition *textPosition = [textView closestPositionToPoint:tapLocation]; NSDictionary *attributes = [textView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward]; NSURL *url = attributes[NSLinkAttributeName]; if (url) { [[UIApplication sharedApplication] openURL:url]; } }
而快速版本:
点击识别器:
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("tappedTextView:")) myTextView.addGestureRecognizer(tapRecognizer) myTextView.selectable = true
打回来:
func tappedTextView(tapGesture: UIGestureRecognizer) { let textView = tapGesture.view as! UITextView let tapLocation = tapGesture.locationInView(textView) let textPosition = textView.closestPositionToPoint(tapLocation) let attr: NSDictionary = textView.textStylingAtPosition(textPosition, inDirection: UITextStorageDirection.Forward) if let url: NSURL = attr[NSLinkAttributeName] as? NSURL { UIApplication.sharedApplication().openURL(url) } }
是UITextView
选择?试试:
self.textView.selectable = YES;
编辑:
我开始认为,与苹果公司所说的相反,长按可能是解决问题的唯一途径.检查此链接,也许会有所帮助.
正如nnarayann所提到的,CCHLinkTextView避免了延迟抽头识别的问题.该库实现了自己的手势识别器,现在可以在1.0版本中使用.