TextKit的相关知识可以看这一篇文章:点我
要使UILabel
用上TextKit
,需要自定义UILabel
先看看使用这个自定义Label的demo
1. 自定义UILabel
并创建TextKit
三个核心对象
/// NSAttributedString 子类 设置文本统一使用
fileprivate lazy var textStorage = NSTextStorage()
/// 布局管理器 负责 字形 布局
fileprivate lazy var layoutManager = NSLayoutManager()
/// 绘制区域
fileprivate lazy var textContainer = NSTextContainer()
2.设置TextKit
/// 准备文本系统
fileprivate func prepareTextSystem() {
adjustsFontSizeToFitWidth = true
// 打开交互
isUserInteractionEnabled = true
// 准备文本内容
prepareText()
// 设置对象的关系
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
}
/// 准备文本内容 - 使用TextStorage 接管 label内容
fileprivate func prepareText() {
if let attributedText = attributedText {
textStorage.setAttributedString(attributedText)
}else if let text = text {
textStorage.setAttributedString(NSAttributedString(string: text))
}else {
textStorage.setAttributedString(NSAttributedString(string: ""))
return
}
-
上一步需要在label初始化的时候执行,所以需要两个构造器里调用此方法
// 代码创建
override init(frame: CGRect) {
super.init(frame: frame)
prepareTextSystem()
}
// xib创建
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareTextSystem()
}
-
指定文本绘制区域
override func layoutSubviews() {
super.layoutSubviews()
textContainer.size = bounds.size
}
-
绘制textStorage的文本内容
override func drawText(in rect: CGRect) {
// 绘制背景
let range = NSRange(location: 0, length: textStorage.length)
layoutManager.drawBackground(forGlyphRange: range, at: CGPoint(x: 0, y: 0))
// 绘制字形
layoutManager.drawGlyphs(forGlyphRange: range, at: CGPoint(x: -5, y: 0))
}
注意:必须先绘制背景才能绘制字形!否则背景会覆盖字形
到此,TextKit基本设置完了。
3. 利用正则寻找需要高亮的内容
例如微博需要高亮
链接
@用户
#话题#
根据正则表达式在textStorage中寻找对应的range
private func findRanges(pattern: String) -> [NSRange]? {
guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else {
return nil
}
let matches = regx.matches(in: textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length))
var ranges = [NSRange]()
for match in matches {
ranges.append(match.rangeAt(0))
}
return ranges
}
- 定义计算型属性保存ranges
/// 链接
var urlRanges: [NSRange]? {
let pattern = "\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))"
return findRanges(pattern: pattern)
}
/// 话题
var topicRanges: [NSRange]? {
let pattern = "#[^#]+#"
return findRanges(pattern: pattern)
}
/// @用户
var atRanges: [NSRange]? {
let pattern = "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]{2,30}"
return findRanges(pattern: pattern)
}
4. 设置属性文本
找到相应的range后就可以设置颜色、背景色等等属性了
fileprivate func setupTextAttributes() {
textStorage.addAttributes([NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor],
range: NSRange(location: 0, length: textStorage.length))
for range in urlRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
for range in topicRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
for range in atRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
}
5. 交互
- 要使
UILabel
可交互前提是打开交互
isUserInteractionEnabled = true
- 点击高亮部分
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
guard let location = touches.first?.location(in: self) else {
return
}
// 获取点击了第几个字符
let index = layoutManager.glyphIndex(for: location, in: textContainer)
// 判断index是否在 range里
for range in urlRanges ?? [] {
if NSLocationInRange(index, range) {
let str = (textStorage.string as NSString).substring(with: range)
print("点击了\(str)链接")
return
}
}
for range in topicRanges ?? [] {
if NSLocationInRange(index, range) {
let str = (textStorage.string as NSString).substring(with: range)
print("点击了\(str)话题")
return
}
}
for range in atRanges ?? [] {
if NSLocationInRange(index, range) {
let str = (textStorage.string as NSString).substring(with: range)
print("点击了\(str)用户"))
return
}
}
}
- 创建代理协议
当点击高亮文本后需要传递事件以及点击的文本出去这时候可以利用代理协议。
protocol XXXLabelDelegate: NSObjectProtocol {
func labelDidSelectedLink(text: String)
func labelDidSelectedTopic(text: String)
func labelDidSelectedAt(text: String)
}
weak var delegate: XXXLabelDelegate?
6. 重写属性
当在外部使用时,例如:
let label = XXXLabel()
label.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
label.text = "@百度 https://www.baidu.com" // 或者 label.attributedText = “@百度 https://www.baidu.com”
label.font = UIFont.systemFont(ofSize: 15)
这时候label是没有任何内容的,因为已经使用TextKit接管了UILabel,所以需要重写属性,给textStorage赋值然后再设置属性文本即可
override var text: String? {
didSet {
prepareText()
}
}
override var attributedText: NSAttributedString? {
didSet {
prepareText()
}
}
override var font: UIFont! {
didSet {
prepareText()
}
}
override var textColor: UIColor! {
didSet {
prepareText()
}
}
fileprivate func prepareText() {
if let attributedText = attributedText {
textStorage.setAttributedString(attributedText)
}else if let text = text {
textStorage.setAttributedString(NSAttributedString(string: text))
}else {
textStorage.setAttributedString(NSAttributedString(string: ""))
return
}
// 设置Text属性
setupTextAttributes()
}
fileprivate func setupTextAttributes() {
textStorage.addAttributes([NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor],
range: NSRange(location: 0, length: textStorage.length))
for range in urlRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
for range in topicRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
for range in atRanges ?? [] {
textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: range)
}
}
GitHub
觉得不错的给个star,非常感谢。