NSLinkAttributeName无法在UITextView中使用

时间:2015-11-07 03:04:49

标签: ios iphone swift uitextview nsattributedstring

我正在开发一个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)

当我点击具有链接属性的单词时,textview委托甚至没有被调用!!!! 有人可以帮我解释它为什么不起作用以及如何使其发挥作用。

谢谢。

1 个答案:

答案 0 :(得分:19)

来自UITextViewDelegate参考:

  

重要事项文本视图中的链接仅在文本视图中是交互式的   可选但不可编辑。也就是说,如果是UITextView的值   selectable属性为YES,isEditable属性为NO。

所以将descriptionView.selectable = false更改为descriptionView.selectable = true