I am working on an IOS app and I am using Swift. I want to make a word clickable and open some URL (for now www.apple.com) on clicking that word.
I am using the following code but it is not working for some reason.
func setDescription(description: NSAttributedString)
{
let descriptionRect = CGRectMake(10, 50, self.bounds.size.width - 20, self.bounds.size.height-20)
let descriptionView = UITextView(frame: descriptionRect)
descriptionView.editable = false
descriptionView.selectable = false
descriptionView.attributedText = description
descriptionView.delegate = self
descriptionView.font = UIFont(name: "Helvetica", size: 14)
NSLog("%@", descriptionView.attributedText)
self.addSubview(descriptionView)
}
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
NSLog("In text view delegate")
return true;
}
The below snippet takes a string and forms attributed string with first 5 chars holding NSLinkNameAttribute. Then I called setDescription function to add this attributed string to TextView.
let mutableAttrString = NSMutableAttributedString(string: attrString1)
let linkURL = NSURL(string: "http://www.apple.com")
mutableAttrString.addAttribute(NSLinkAttributeName,value: linkURL!,range: NSMakeRange(0, 5))
wordDetailView.setDescription(mutableAttrString)
When I click on the word which has the link attribute textview delegate is not even getting called!!!! Could someone please help me out on why it is not working and how make it work.
Thank you.
From the UITextViewDelegate reference:
IMPORTANT Links in text views are interactive only if the text view is selectable but noneditable. That is, if the value of the UITextView selectable property is YES and the isEditable property is NO.
So change descriptionView.selectable = false
to descriptionView.selectable = true
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