UITextView:禁用选择,允许链接 [英] UITextView: Disable selection, allow links

查看:144
本文介绍了UITextView:禁用选择,允许链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UITextView 显示 NSAttributedString 。 textView的可编辑可选择的属性都设置为 false

I have a UITextView which displays an NSAttributedString. The textView's editable and selectable properties are both set to false.

attributionString包含一个URL,我想允许点击URL来打开浏览器。但只有在可选属性设置为 true 时,才能与URL进行交互。

The attributedString contains a URL and I'd like to allow tapping the URL to open a browser. But interaction with the URL is only possible if the selectable attribute is set to true.

如何才允许用户互动仅用于点击链接,而不是用于选择文字?

推荐答案

我发现摆弄内部手势识别器的概念有点吓人,所以试图寻找另一种解决方案。
我发现我们可以覆盖 point(inside:with :) ,以便在用户没有触及时有效地允许点击其中包含链接的文本:

I find the concept of fiddling with the internal gesture recognizers a little scary, so tried to find another solution. I've discovered that we can override point(inside:with:) to effectively allow a "tap-through" when the user isn't touching down on text with a link inside it:

// Inside a UITextView subclass:
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {

    guard let pos = closestPosition(to: point) else { return false }

    guard let range = tokenizer.rangeEnclosingPosition(pos, with: .character, inDirection: UITextLayoutDirection.left.rawValue) else { return false }

    let startIndex = offset(from: beginningOfDocument, to: range.start)

    return attributedText.attribute(NSLinkAttributeName, at: startIndex, effectiveRange: nil) != nil 
}   

这也意味着如果你有一个 UITextView ,其中包含一个 UITableViewCell tableView(didSelectRowAt :)的链接

This also means that if you have a UITextView with a link inside a UITableViewCell, tableView(didSelectRowAt:) still gets called when tapping the non-linked portion of the text :)

这篇关于UITextView:禁用选择,允许链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆