需求
我們需要實(shí)現(xiàn)一個(gè)類似于下圖的功能掏缎,常見(jiàn)的是在app
中查看協(xié)議之類的龙亲。
示意圖
問(wèn)題:
- 局部高亮
- 點(diǎn)擊后跳轉(zhuǎn)
- 僅僅是高亮的部分作為按鍵的相應(yīng)熱區(qū) —— 似乎一些像
YYLabel
的第三方庫(kù)有實(shí)現(xiàn)。但是一些應(yīng)用場(chǎng)景下有咨,只將高兩部分作為熱區(qū)寒波,不容易點(diǎn)到。另外是涉及第三方庫(kù)的應(yīng)用螟凭,這里先不做討論 - 為了增加交互,將整個(gè)
UILabel
的區(qū)域作為熱區(qū)它呀。
- 僅僅是高亮的部分作為按鍵的相應(yīng)熱區(qū) —— 似乎一些像
- 文本的展示螺男,必須兼容多語(yǔ)言
實(shí)現(xiàn)思路
實(shí)際就是利用UILabel
的 attributedText
屬性,對(duì)text
的不同range
做不同的富文本屬性設(shè)置
代碼
暫時(shí)只提供 swift
代碼
class ShowServiceAgreementTipView: UILabel {
private var onCheckAgreement: () -> ()
init(onCheckAgreement: @escaping OnCallbackWithNoParams) {
self.onCheckAgreement = onCheckAgreement
super.init(frame: CGRect.zero)
let normalText = myLocal("register_equals_accept") // 語(yǔ)言國(guó)際化
let serviceText = myLocal("service_protocol") // 語(yǔ)言國(guó)際化
let tipText = normalText + " " + serviceText
let wholeRange = (tipText as NSString).range(of: tipText)
let normalRange = (tipText as NSString).range(of: normalText)
let serviceRange = (tipText as NSString).range(of: serviceText)
let tipAttributeText = NSMutableAttributedString(string: tipText)
// 針對(duì)不同區(qū)域添加富文本屬性
tipAttributeText.addAttribute(NSAttributedStringKey.font, value: UIFont(),
range: wholeRange)
tipAttributeText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hexString: "#999999")!,
range: normalRange)
tipAttributeText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hexString: "#6F99C4")!,
range: serviceRange)
attributedText = tipAttributeText
numberOfLines = 0 //設(shè)置自動(dòng)換行
textAlignment = .center // 設(shè)置居中
isUserInteractionEnabled = true // UILabel 默認(rèn)不響應(yīng)事件纵穿,這里需要另外添加
let gesture = UITapGestureRecognizer(target: self, action: #selector(tapToCheckProtocol))
addGestureRecognizer(gesture)
}
@objc private func tapToCheckProtocol() {
onCheckAgreement()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}