一、前言
废话不说,想实现的效果如下图,使用UITextView实现链接点击跳转的效果,UILabel可以实现效果,但是不支持部分文字点击效果。(支持方法比较麻烦)
UITextView多链接
二、实现方法
1、在NSMutableAttributedString创建extension,用来创建连接文本和对应的链接
<pre>
extension NSMutableAttributedString {
public func addLink(_ source: String, link: String, attributes: [String : Any]? = nil) {
let linkString = NSMutableAttributedString(string: source, attributes: attributes)
let range: NSRange = NSRange(location: 0, length: linkString.length)
linkString.beginEditing()
linkString.addAttribute(NSLinkAttributeName, value: link, range: range)
linkString.endEditing()
self.append(linkString)
}
public func append(_ string: String, attributes: [String : Any]? = nil) {
let attrString = NSAttributedString(string: string, attributes: attributes)
self.append(attrString)
}
}
</pre>
2、创建UITextView,设置attributeStirng,实现代理
UITextViewDelegate.
<pre>
view.delegate = USLinkTextManger.instance
view.isEditable = false
let attributes = [NSForegroundColorAttributeName: USColor.c301.color,NSFontAttributeName: USFont.t05.font]
let attrString = NSMutableAttributedString()
attrString.append(NSAttributedString(string: "有疑问,欢迎拨打", attributes: attributes))
attrString.addLink("17711678021", link: "protocol1://", attributes: attributes)
attrString.append(NSAttributedString(string: "也可以通过邮箱联系我们", attributes: attributes))
attrString.addLink("xiniu@wtest.com", link: "protocol2://", attributes: attributes)
view.attributedText = attrString
</pre>
实现代理,协议是自定义的
<pre>
@available(iOS 10.0, *)
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
guard let scheme = url.scheme else {
return false
}
switch scheme {
case "protocol1":
print("protocol1")
case "protocol2":
print("protocol2")
default:
break
}
return true
}
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
guard let scheme = url.scheme else {
return false
}
switch scheme {
case "tel":
print("tel")
case "mail":
print("mail")
default:
break
}
return true
}
</pre>
在代理中,根据自己定义的协议实现不同的方法,可以跳转到原生,也可以新开h5页面
三、需要注意
1、如果需要自定义链接颜色,可以使用UITextView的linkTextAttributes属性
view.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.red]]
2、如果是自定义链接,UITextView应该禁止编辑,使用isEditable属性.禁止上下滚动使用isScrollEnable
网友评论