Swift简单实现一个常规条款、免责声明文字+带有链接的展示形式

时间:2022-05-08 09:44:19

效果:

 
Swift简单实现一个常规条款、免责声明文字+带有链接的展示形式
IMG_F08DABE063A6-1.jpeg
class DisclamerView: UIView { //@objc weak var vc:UIViewController? //自定义协议 @IBInspectable var diy_protocol:String = "diyprotocol" //超链接地址 @IBInspectable var disclamerURLStr:String = " " //条款、免责声明描述文字 @IBInspectable var infoStr = str_disclaimer //链接地址描述 @IBInspectable var linkStr = "" //展示文字的大小(用于判断展示区域大小) @IBInspectable var font = UIFont.systemFont(ofSize: 13) lazy var infoTextView:UITextView = { let tv = UITextView() tv.delegate = self tv.isEditable = false tv.backgroundColor = UIColor.clear tv.isScrollEnabled = false //设置页边距上边距10,左右边距各10,底边距0 上,右,下,左 tv.textContainerInset = UIEdgeInsetsMake(10, 0, 0, -5); self.addSubview(tv) return tv }() override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.groupTableViewBackground } override func draw(_ rect: CGRect) { // Drawing code let attri = NSMutableAttributedString(attributedString: NSAttributedString(string: infoStr + linkStr, attributes:[NSAttributedStringKey.foregroundColor : UIColor.darkGray, NSAttributedStringKey.font : font])) if linkStr != ""{ attri.addAttributes([NSAttributedStringKey.link:(diy_protocol+"://")], range: ((attri.string) as NSString).range(of: linkStr)) } infoTextView.attributedText = attri //左右两天预留5个像素 infoTextView.frame = CGRect(x: 5, y: 0, width: rect.width - 5*2, height: rect.height) } } extension DisclamerView:UITextViewDelegate{ //textView里带有超链接的监听代理 func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { //判断超链接协议 if let sch = URL.scheme,sch == diy_protocol { //let ndvc = SFNewsDetailVC(nibName: "SFNewsDetailVC", bundle: nil) // ndvc.requstURL = disclamerURLStr; //if let vc = vc as? UINavigationController{ // vc.pushViewController(ndvc, animated: true) // }else{ // ndvc.isPresent = true // vc?.present(ndvc, animated: true, completion: nil) /// } return true } return false } } 

XIB使用:

self.disclamerView.linkStr = @"点击查看详情"; // CGFloat dh = [STools getDisclaimerStrContentHeightWithDSize:CGSizeMake(SWIDTH - 5*2, 10000) dFont:self.disclamerView.font] + 18; self.h_disclamerView.constant = dh; 
 
Swift简单实现一个常规条款、免责声明文字+带有链接的展示形式
image.png
 
Swift简单实现一个常规条款、免责声明文字+带有链接的展示形式
image.png

纯代码使用

    lazy var disclamerView:DisclamerView = { let dv = DisclamerView() dv.backgroundColor = color_background let dh = STools.getDisclaimerStrContentHeight(dFont: dv.font) + 18 dv.frame = CGRect(x: 0, y: 0,width: swidth, height: dh) dv.vc = self return dv }() self.tableView.tableFooterView = disclamerView