我正在开发一个 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 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
关于ios - NSLinkAttributeName 在 UITextView 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33578693/