UITextView中的链接无法在Swift 4中运行

问题描述 投票:6回答:1

我正在使用iOS 11和Swift 4。

我试图以编程方式生成UITextView内的链接。

所有属性都起作用(即颜色,大小,范围等) - 但不幸的是,链接不起作用。谁能告诉我为什么?

这是我的代码:

@IBOutlet weak var textView: UITextView!

// Setting the attributes
let linkAttributes = [
    NSAttributedStringKey.link: URL(string: "https://www.apple.com")!,
    NSAttributedStringKey.font: UIFont(name: "Helvetica", size: 18.0)!,
    NSAttributedStringKey.foregroundColor: UIColor.blue
    ] as [NSAttributedStringKey : Any]

let attributedString = NSMutableAttributedString(string: "Just click here to do stuff...")

// Set the 'click here' substring to be the link
attributedString.setAttributes(linkAttributes, range: NSMakeRange(5, 10))

self.textView.delegate = self
self.textView.attributedText = attributedString

再次,链接似乎是正确的,但点击它不起作用。

这是截图:

Screenshot of the UITextView

ios swift swift4 uitextview nsattributedstring
1个回答
22
投票

您应该为文本视图启用isSelectable并禁用isEditable

textView.isSelectable = true
textView.isEditable = false

您还可以在文本视图的“属性”检查器的“行为”部分中的Interface Builder中设置这些行为:

Interface Builder - Attributes inspector/Behavior

© www.soinside.com 2019 - 2024. All rights reserved.