需求
我們需要實現一個類似于下圖的功能,常見的是在app
中查看協議之類的。
示意圖
問題:
- 局部高亮
- 點擊后跳轉
- 僅僅是高亮的部分作為按鍵的相應熱區 —— 似乎一些像
YYLabel
的第三方庫有實現。但是一些應用場景下,只將高兩部分作為熱區,不容易點到。另外是涉及第三方庫的應用,這里先不做討論 - 為了增加交互,將整個
UILabel
的區域作為熱區。
- 僅僅是高亮的部分作為按鍵的相應熱區 —— 似乎一些像
- 文本的展示,必須兼容多語言
實現思路
實際就是利用UILabel
的 attributedText
屬性,對text
的不同range
做不同的富文本屬性設置
代碼
暫時只提供 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") // 語言國際化
let serviceText = myLocal("service_protocol") // 語言國際化
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)
// 針對不同區域添加富文本屬性
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 //設置自動換行
textAlignment = .center // 設置居中
isUserInteractionEnabled = true // UILabel 默認不響應事件,這里需要另外添加
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")
}
}