demo GitHub
原理
UITextView 设置attributedText,attributedText中可以添加点击链接,点击执行回调。在一个view中添加两个一样的textView,上面textView的关闭响应isUserInteractionEnabled,下面的textview关闭isEditable。将两个textview添加到view上添加约束大小和view一样。
- 设置textview attributedText
/// 点击响应部分字符串
private var clickStr:String? {
didSet{
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = NSLineBreakMode.byCharWrapping
keyRange = content!.range(of: clickStr!)
let att:NSMutableAttributedString = NSMutableAttributedString(string: content!)
att.addAttribute(NSAttributedStringKey.link, value: URL(string: clickKey)!, range: "".nsRange(from: keyRange!))
att.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: textFont), range: NSMakeRange(0, content!.count))
att.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, content!.count))
self.contentView.attributedText = att
let att1:NSMutableAttributedString = NSMutableAttributedString(string: content!)
att1.addAttribute(NSAttributedStringKey.foregroundColor, value: keyColor!, range: "".nsRange(from: keyRange!))
att1.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: textFont), range:NSMakeRange(0, content!.count))
att1.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, content!.count))
self.subContentView.attributedText = att1
}
}
- 设置textview 回调
//点击textview中的url 回调
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if URL.absoluteString == clickKey {
if let tmp = clickBlock {
tmp(clickStr)
}
}
return false
}
- 主要代码在项目中CCClickStringLabel目录,还有部分功能未完善,还有一些别的功能封装类
网友评论