iOS用戶協(xié)議界面實現(xiàn)方案(YYText實現(xiàn)部分文字的高亮點擊)
通常情況下注冊腥泥、登錄界面下方都會包含用戶協(xié)議和隱私政策的界面如下:
實現(xiàn)思路
- 左側(cè)選中框是個check按鈕
- 閱讀并同意用戶協(xié)議和隱私政策部分是富文本
- 給富文本中的“用戶協(xié)議”裹唆、“隱私政策”添加點擊事件
實現(xiàn)方案
1. 繼承UIView創(chuàng)建一個獨立視圖方便復用
2. 在視圖上添加check按鈕
3. 用YYText實現(xiàn)富文本和點擊事件
實現(xiàn)代碼
/// 用戶協(xié)議視圖
class UTUserAgreementView: UIView {
/// 協(xié)議類型
///
/// - user: 用戶協(xié)議
/// - privacy: 隱私政策
enum agreementType{
case user
case privacy
}
/// 選中事件
let selectPS = PublishSubject<agreementType>()
//界面高20 款240
/// 核查選擇框
lazy var checkBox: UIButton = {
let view = UIButton()
view.setImage(UIImage.init(named: "login_weigouxuan"), for: UIControl.State.normal)
view.setImage(UIImage.init(named: "login_gouxuan"), for: UIControl.State.selected)
view.addTarget(self, action: #selector(checkBoxAction(sender:)), for: .touchUpInside)
view.isSelected = true
self.addSubview(view)
return view
}()
/// 協(xié)議文本
lazy var agreeMentLB: YYLabel = {
//創(chuàng)建YYLabel
let view = YYLabel()
//創(chuàng)建富文本熊榛,設置默認font和color
let text = NSMutableAttributedString.init(string: "閱讀并同意用戶協(xié)議和隱私政策", attributes: [.font : UIFont.systemFont(ofSize: 14)])
text.yy_color = UIColor.UT79Color()
let decoration = YYTextDecoration.init(style: YYTextLineStyle.single, width: 1, color: UIColor.UT79Color())
//第一個特殊顯示區(qū)域,設置對應的font和color
let rangeOne = NSRange.init(location: 5, length: 4)
text.yy_setTextHighlight(rangeOne, color: UIColor.UT20Color(), backgroundColor: UIColor.clear, tapAction: { (view, string, range, rect) in
//點擊事件回調(diào)
self.selectPS.onNext(.user)
})
//第二個特殊顯示區(qū)域斯入,設置對應的font和color
let rangeTwo = NSRange.init(location: 10, length: 4)
text.yy_setTextHighlight(rangeTwo, color: UIColor.black, backgroundColor: UIColor.clear, tapAction: { (view, string, range, rect) in
//點擊事件回調(diào)
self.selectPS.onNext(.privacy)
})
text.yy_setTextUnderline(decoration, range: rangeOne)
text.yy_setTextUnderline(decoration, range: rangeTwo)
//加載富文本
view.attributedText = text
self.addSubview(view)
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
deploySubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func deploySubviews(){
agreeMentLB.snp.makeConstraints { (make) in
make.centerX.equalToSuperview().offset(12.5)
make.top.bottom.equalToSuperview()
}
checkBox.snp.makeConstraints { (make) in
make.centerY.equalTo(agreeMentLB.snp.centerY).offset(-0.5)
make.width.height.equalTo(20)
make.right.equalTo(agreeMentLB.snp.left).offset(-5)
}
}
/// 核驗按鈕
///
/// - Parameter sender: 按鈕對象
@objc private func checkBoxAction(sender: UIButton){
sender.isSelected = !sender.isSelected
}
}