最近在看Swift,之前在OC用到過(guò)TTTAttributedLabel 感覺(jué)還不錯(cuò),就想試一下用Swift實(shí)現(xiàn)一下。這里實(shí)現(xiàn)一個(gè)簡(jiǎn)單的功能,直接上圖。。

QQ20170608-152002@2x.png
我使用pod 導(dǎo)的 TTTAttributedLabel 這比較方便。
首先先懶加載初始化一個(gè)Label
//懶加載初始化 TTTAttributedLabel
lazy var tttAttributedLabel: TTTAttributedLabel = {
var tttAttributedLabel = TTTAttributedLabel.init(frame: CGRect.init(x: 0, y: 100, width: UIScreen.main.bounds.size.width, height: 50))
tttAttributedLabel.numberOfLines = 0
//這里是給fromname 設(shè)置字體顏色 還可以設(shè)置字體大小等。
tttAttributedLabel.linkAttributes = [NSForegroundColorAttributeName: UIColor.red]
// tttAttributedLabel.linkAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 15)]
return tttAttributedLabel
}()
這里寫(xiě)兩個(gè)假數(shù)據(jù)
let content = NSString.init(string: "小張:你好,你好,你好,你好!")
let fromname = NSString.init(string: "小張")
然后 可以設(shè)置Lable的屬性 字體大小 顏色等
//這里可以更改Label 的屬性 字體大小字體顏色等
let attr = [
NSFontAttributeName: UIFont.systemFont(ofSize: 20),
NSForegroundColorAttributeName: UIColor.black
]
//這里兩個(gè)參數(shù) 第一個(gè)參數(shù) 是label全部的內(nèi)容。
// 第二個(gè)參數(shù)是 上面的屬性
let contentAttributedString = NSAttributedString.init(string: content as String, attributes: attr)
然后就是賦值了
//給lable賦值 用 attributedText
tttAttributedLabel.attributedText = contentAttributedString
接下來(lái)設(shè)置紅色字體部分
//這里是添加 哪一部分 是其他顏色 這個(gè)就是那個(gè)fromname
//主要有三個(gè)參數(shù) 第一個(gè)參數(shù)是紅色字體的內(nèi)容
//第二個(gè)參數(shù)是從哪開(kāi)始
//第三個(gè)參數(shù)是 紅色的長(zhǎng)度
let fromLink = tttAttributedLabel .addLink(toPhoneNumber: fromname as String!, with: NSRange.init(location: 0, length: fromname.length+1))
然后設(shè)置紅色部分的點(diǎn)擊事件
//這里是給fromname 添加點(diǎn)擊事件
fromLink?.linkTapBlock = TTTAttributedLabelLinkBlock!.init({ (TTTAttributedLabel, TTTAttributedLabelLink) in
print(TTTAttributedLabel?.text! ?? String())
})
到這里就差不多結(jié)束了,付一個(gè)小demo的鏈接
http://git.oschina.net/Allen__yao/swift_tttattributedlabeldemo
剛開(kāi)始研究Swift 還請(qǐng)大神們多多指教。。