直接上代码了,很简单,不是很复杂
1.类库方法如下
import Foundation
import UIKit
///点击类型
enum ProtocolType {
case userProtocol
case privacyPolicy
}
/// 同意协议view
class LoginPolicyAgreeView: UIView, UITextViewDelegate {
///点击事件
var clickHandle:((_ clickType:ProtocolType)->())?
///同意View
private lazy var agreeTextView : UITextView = {
let textStr = "谢谢谢谢谢谢谢谢谢谢你的关注和收藏,一起进步 协议 & 隐私"
let textView = UITextView()
textView.delegate = self
///设为true 在代理里面禁掉所有的交互事件 textAlignment
textView.isEditable = true
textView.autoresizingMask = UIView.AutoresizingMask.flexibleHeight
textView.isScrollEnabled = false
let attStr = NSMutableAttributedString(string: textStr)
attStr.font = UIFont.init(name: "PingFangSC-Regular", size: 14)
attStr.minimumLineHeight = 26
attStr.color = .rgb(250, 217, 75)
attStr.alignment = .center
//点击超链接
attStr.addAttribute(NSAttributedString.Key.link, value: "userProtocol://", range: (textStr as NSString).range(of: "协议"))
//点击超链接
attStr.addAttribute(NSAttributedString.Key.link, value: "privacyPolicy://", range: (textStr as NSString).range(of: "隐私"))
textView.attributedText = attStr
///只能设置一种颜色
textView.linkTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.rgb(165, 212, 251) ,
]
return textView
}()
override init(frame: CGRect) {
super.init(frame: frame)
configUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension LoginPolicyAgreeView{
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return false
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if URL.scheme == "userProtocol"{
self.clickHandle?(.userProtocol)
return false
}else if URL.scheme == "privacyPolicy"{
self.clickHandle?(.privacyPolicy)
return false
}
return true
}
}
extension LoginPolicyAgreeView{
private func configUI(){
///同意view
agreeTextView.backgroundColor = .clear
self.addSubview(agreeTextView)
agreeTextView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
}
2.调用方法
let policyAgreeView = LoginPolicyAgreeView(frame: CGRect(x: 30, y: YJScreen.height - 100 , width: YJScreen.width - 60, height: 100))
self.policyAgreeView.clickHandle = { [weak self] (privacyType) in
if privacyType == .userProtocol {
print("点击了同意666222")
YJRoute.toAgreementVC()
}
if privacyType == .privacyPolicy {
print("点击了同意协议8666333")
YJRoute.toPrivacyVC()
}
}