效果图 输出板最近自己在写一个SwiftApp, 涉及到富文本这块, 上镜率也不是很高, 稍微做下笔记
// 1.定义一个字符串
// 将String类型转换成 NSString,否则在第五步获取range时类型转换很麻烦
let contentStr = " Swift3.0 富文本的使用@111111,改变行间距、添加点击事件@222222" as NSString
// 2.初始化富文本
let nameStr : NSMutableAttributedString = NSMutableAttributedString(string:contentStr as String)
// 3.添加样式 (行间距和对其方式)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 6
paragraphStyle.alignment = .left
// 4.行间距
nameStr.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, contentStr.length))
// 5.关键代码 添加事件
let range = contentStr.range(of: "@111111", options: .regularExpression, range: NSMakeRange(0,contentStr.length))
let range1 = contentStr.range(of: "@222222", options: .regularExpression, range: NSMakeRange(0,contentStr.length))
nameStr.addAttribute(NSLinkAttributeName, value: "frist://", range: range)
nameStr.addAttribute(NSLinkAttributeName, value: "second://", range: range1)
// 6.赋值
textView.attributedText = nameStr
textView.isEditable = false
textView.delegate = self
textView.font = UIFont.systemFont(ofSize: 12)
youView.addSubview(textView)
textView.snp.makeConstraints { (make) in
//...
}
然后在UITextViewDelegate
中处理事件
// MARK: - UITextViewDelegate
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if URL.scheme == "frist" {
print("点击@111111")
return false
}
if URL.scheme == "second" {
print("点击222222")
return false
}
return true
}
暂时涉及到的用法就这些, 以后用得到继续补充
网友评论