Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

ios - UITextView: Disable selection, allow links

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

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.

How can I allow user interaction only for tapping links, but not for selecting text?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: .layout(.left)) else { return false }

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

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

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...