I use this code:
var textView = UITextView(x: 10, y: 10, width: CardWidth - 20, height: placeholderHeight) //This is my custom initializer
textView.text = "dsfadsaf www.google.com"
textView.selectable = true
textView.dataDetectorTypes = UIDataDetectorTypes.Link
textView.delegate = self
addSubview(textView)
The problem is the link needs long tap gesture to open. I want it to open with a single tap, just like in the Facebook app.
The example below only works on iOS 8+
Tap recognizer:
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("tappedTextView:"))
myTextView.addGestureRecognizer(tapRecognizer)
myTextView.selectable = true
Callback:
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)
}
}
Swift 3 and no force unwraps:
func tappedTextView(tapGesture: UIGestureRecognizer) {
guard let textView = tapGesture.view as? UITextView else { return }
guard let position = textView.closestPosition(to: tapGesture.location(in: textView)) else { return }
if let url = textView.textStyling(at: position, in: .forward)?[NSLinkAttributeName] as? URL {
UIApplication.shared.open(url)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With