NSLinkAttributeName无法在UITextView中使用

sr1*_*116 4 iphone uitextview nsattributedstring ios swift

我正在开发一个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;
}
Run Code Online (Sandbox Code Playgroud)

下面的代码片段接受一个字符串,并形成属性字符串,前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)
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

bey*_*ulf 20

来自UITextViewDelegate参考:

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

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

  • 您是在设备上还是在模拟器中进行测试?有时在模拟器中,水龙头不会注册链接.尝试长按在单词的中心,它将起作用. (4认同)