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

iKK*_*iKK 8 uitextview nsattributedstring ios swift swift4

我正在使用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
Run Code Online (Sandbox Code Playgroud)

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

这是截图:

UITextView的屏幕截图

Tam*_*gel 27

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

textView.isSelectable = true
textView.isEditable = false
Run Code Online (Sandbox Code Playgroud)

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

Interface Builder  - 属性检查器/行为