我试图在UITextview中显示带有可点击链接的属性字符串.我已经创建了一个简单的测试项目,看看我哪里出错了,但仍无法弄明白.我已经尝试启用用户交互并设置了shouldInteractWithURLs委托方法,但它仍然无法正常工作.这是我的代码(对于只包含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 }
以下是我实施的委托方法:
func textViewShouldBeginEditing(textView: UITextView) -> Bool { return false } func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { return true }
这仍然无效.我搜索过这个主题,但没有任何帮助.非常感谢提前.
只需UITextView
在故事板中选择,然后转到"显示属性检查器"并选择selectable
和links
.如下图所示.确保Editable
未选中.