Created
September 19, 2017 20:35
-
-
Save nathanborror/4cc8ce931dc46e5e8870074bc3e961e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TextViewCell: UITableViewCell { | |
var onTap: ((URL) -> Void)? | |
lazy var textView: UITextView = { | |
let view = UITextView() | |
view.translatesAutoresizingMaskIntoConstraints = false | |
view.backgroundColor = UIColor(red: 1.0, green: 0, blue: 0, alpha: 0.1) | |
view.textContainer.lineFragmentPadding = 0 | |
view.textContainerInset = .zero | |
view.isEditable = false | |
view.isScrollEnabled = false | |
self.contentView.addSubview(view) | |
NSLayoutConstraint.activate([ | |
view.topAnchor.constraint(equalTo: self.contentView.topAnchor), | |
view.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), | |
view.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 16), | |
view.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -16), | |
]) | |
let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTextHit)) | |
view.addGestureRecognizer(gesture) | |
return view | |
}() | |
@objc func handleTextHit(recognizer: UITapGestureRecognizer) { | |
guard let view = recognizer.view as? UITextView else { | |
return | |
} | |
let manager = view.layoutManager | |
var location = recognizer.location(in: view) | |
location.x = location.x - view.textContainerInset.left | |
location.y = location.y - view.textContainerInset.top | |
var charIndex = 0 | |
charIndex = manager.characterIndex(for: location, in: view.textContainer, fractionOfDistanceBetweenInsertionPoints: nil) | |
if (charIndex < view.textStorage.length) { | |
var range = NSRange() | |
guard let value = view.attributedText.attribute(.custom, at: charIndex, effectiveRange: &range) as? String else { | |
return | |
} | |
guard let url = URL(string: value) else { | |
return | |
} | |
onTap?(url) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment