咋地.png
一、前言
廢話不說,想實現的效果如下圖,使用UITextView實現鏈接點擊跳轉的效果,UILabel可以實現效果,但是不支持部分文字點擊效果。(支持方法比較麻煩)
UITextView多鏈接
二、實現方法
1、在NSMutableAttributedString創建extension,用來創建連接文本和對應的鏈接
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)
}
}
2、創建UITextView,設置attributeStirng,實現代理
UITextViewDelegate.
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
實現代理,協議是自定義的
@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
}
在代理中,根據自己定義的協議實現不同的方法,可以跳轉到原生,也可以新開h5頁面
三、需要注意
1、如果需要自定義鏈接顏色,可以使用UITextView的linkTextAttributes屬性
view.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.red]]
2、如果是自定義鏈接,UITextView應該禁止編輯,使用isEditable屬性.禁止上下滾動使用isScrollEnable