Link in UITextView not working in Swift 4

断了今生、忘了曾经 提交于 2020-01-03 08:31:33

问题


I'm using iOS 11 and Swift 4.

I am trying to programmatically generate a link inside a UITextView.

All the attributes work (i.e. color, size, range etc.) - but unfortunately, the link does not work. Can anybody tell me why?

Here is my code:

@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

Again, the link seems correct, but clicking it does not work.

Here is the screenshot:


回答1:


You should enable isSelectable and disable isEditable for your text view.

textView.isSelectable = true
textView.isEditable = false

You can also set up these behaviors inside Interface Builder in the Behavior section of the text view's Attributes inspector:



来源:https://stackoverflow.com/questions/46584071/link-in-uitextview-not-working-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!