ios - NSLinkAttributeName 在 UITextView 中不起作用

标签 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 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/

相关文章:

iphone - iPhone 中的 Foursquare 集成

ios - 在 UITabBarController 内的 View Controller 之间传递数据,无需使用 segues

ios - 无法将类型 "String"的值分配给 swift 类型 "UILabel"

ios - PerformSegueWithIdentifier 触发,但不显示

ios - Xamarin for iOS 中的分辨率独立性

ios - 如何在 hidesBottomBarWhenPushed 为 "TRUE"时隐藏自定义标签栏按钮

ios - 在自定义键盘扩展中支持多种语言

iphone - 字典未复制到其他字典,异常 : Dictionary argument is not a NSDictionary

ios - 如何在 iOS 中更改 Chirp 的 SDK 状态?

iphone - 手动滚动显示相同内容的两个 UICollectionView