背景
在开发中,有时需要展示一句带有某些可接受用户响应的关键词的文案,比如在页面上显示某某协议之类的。如果一行能完全显示(各种设备上),那么就可以在界面上写死布局;如果不能显示,则就需要使用
UITextView
控件了。
效果图
图中,《XXXX规则》是可点击的,并且可以完美的适配各个设备。废话少说,直接上代码 ↓
核心代码
override func viewDidLoad() {
super.viewDidLoad()
let str1 = "我已知晓XXXXXX产品风险、XXXXXX交易规则并确认根据"
let linkedStr = "《XXXX规则》"
let str2 = "执行交易。"
let str = "\(str1)\(linkedStr)\(str2)"
let attributedString = NSMutableAttributedString(string: str)
let startIndex = str1.characters.count
let endIndex = linkedStr.characters.count
let range = NSMakeRange(startIndex, endIndex)
attributedString.addAttribute(NSLinkAttributeName, value: "gotoAgreement", range: range)
textView.attributedText = attributedString
let attrs = [NSForegroundColorAttributeName: UIColor.red]
textView.linkTextAttributes = attrs
maticallyAdjustsScrollViewInsets = false
textView.isEditable = false
View.isSelectable = true
}
// MARK: -
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if URL.absoluteString == "gotoAgreement" {
// 处理点击事件
navigationController?.pushViewController(SecondViewController(), animated: true)
return false
}
return true
}
Demo下载
点我进入下载页面