NSLinkAttributeName 在 UITextView 中不起作用

NSLinkAttributeName not working in UITextView

我正在开发 IOS 应用程序,我正在使用 Swift。我想让一个词可点击并在点击那个词时打开一些 URL(现在 www.apple.com)。

我正在使用以下代码,但由于某种原因无法正常工作。

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;
}

下面的代码片段采用一个字符串并形成具有前 5 个字符的属性字符串 持有 NSLinkNameAttribute。然后我调用 setDescription 函数将这个属性字符串添加到 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)

当我点击具有 link 属性的单词时,textview delegate 甚至没有被调用!!!! 有人可以帮我解释为什么它不起作用以及如何让它起作用吗?

谢谢。

来自 UITextViewDelegate 参考:

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.

所以把descriptionView.selectable = false改成descriptionView.selectable = true