如何在UITextView中显示可点击的链接 [英] How to display clickable links in UITextView
问题描述
我正在尝试使用可点击的链接在UITextview中显示属性字符串。我已经创建了一个简单的测试项目,看看我哪里出错,但仍然无法弄明白。我已经尝试启用用户交互并设置了shouldInteractWithURLs委托方法,但它仍然无法正常工作。这是我的代码(对于只包含textview的视图控制器)
I am trying to display an attributed string in a UITextview with clickable links. I've created a simple test project to see where I'm going wrong and still can't figure it out. I've tried enabling user interaction and setting the shouldInteractWithURLs delegate method, but it's still not working. Here's my code (for a view controller that only contains a textview)
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let string = "Google"
let linkString = NSMutableAttributedString(string: string)
linkString.addAttribute(NSLinkAttributeName, value: NSURL(string: "https://www.google.com")!, range: NSMakeRange(0, string.characters.count))
linkString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue", size: 25.0)!, range: NSMakeRange(0, string.characters.count))
textView.attributedText = linkString
textView.delegate = self
textView.selectable = true
textView.userInteractionEnabled = true
}
以下是我实施的委托方法:
And here are the delegate methods I've implemented:
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
return false
}
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
return true
}
这仍然无效。我搜索过这个主题,但没有任何帮助。非常感谢提前。
This still isn't working. I've searched on this topic and nothing has helped yet. Thanks so much in advance.
推荐答案
只需选择 UITextView
即可故事板并转到显示属性检查器并选择可选择
和链接
。如下图所示。确保未选中可编辑
。
Just select the UITextView
in your storyboard and go to "Show Attributes inspector" and select selectable
and links
. As the image below shows. Make sure Editable
is unchecked.
这篇关于如何在UITextView中显示可点击的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!