I am working on an iOS application and I am using Swift. I want to make the word clickable and open some URL (currently www.apple.com) when this word is clicked.
I use the following code, but for some reason it does not work.
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;
}
Below the fragment takes a string and forms an attribute string with the first 5 characters holding NSLinkNameAttribute. Then I called the setDescription function to add this attribute string to the 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 a word that has a link textview attribute, the delegate is not even called !!!! Can someone please help me why it does not work and how it works.
Thanks.
source
share