Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLinkAttributeName not working in UITextView

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.

like image 409
sr116 Avatar asked Nov 29 '22 14:11

sr116


1 Answers

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

like image 115
beyowulf Avatar answered Dec 15 '22 15:12

beyowulf