ios - 以编程方式快速标记 NSMutableAttributedString 4
问题描述
我必须确保我可以点击“隐私”一词才能打开网页链接。我尝试了我发现的建议,但它们是旧东西,它们似乎不再起作用..我不知道如何解决这个问题
private lazy var firstTermDescriptionLabel: UILabel = {
let label = UILabel(frame: .zero)
let firstTermsMessage = "I Agree to the License Terms and Privacy Policy"
var attributedString = NSMutableAttributedString.init(string: "Privacy")
attributedString.addAttribute(.link, value: "https://www.google.com/url?q=https://www.iubenda.com/privacy-policy/58446596&sa=D&source=hangouts&ust=1528787597335000&usg=AFQjCNEPkofPxSm7TDRMvxjOjCz5cio27w", range: NSRange(location: 0, length: 7))
label.isUserInteractionEnabled = true
label.text = firstTermsMessage
label.font = UIFont.systemFont(ofSize: 13, weight: .regular)
label.textAlignment = .left
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
label.heightAnchor.constraint(equalToConstant: 36).isActive = true
return label
}()
解决方案
更新到 Swift 4
将此扩展添加到您的项目中
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.range(of: textToFind)
if foundRange.location != NSNotFound {
// self.addAttribute(NSLinkAttributeName, value: linkURL, range: foundRange)
self.addAttributes([NSAttributedStringKey.link: URL(string: linkURL)!], range: foundRange)
return true
}
return false
}
}
在下面更改您的喜欢:
let firstTermsMessage = "I Agree to the License Terms and Privacy Policy"
let attributedString = NSMutableAttributedString(string:firstTermsMessage)
let linkWasSet = attributedString.setAsLink(textToFind: "Privacy", linkURL: "https://www.google.com/url?q=https://www.iubenda.com/privacy-policy/58446596&sa=D&source=hangouts&ust=1528787597335000&usg=AFQjCNEPkofPxSm7TDRMvxjOjCz5cio27w")
if linkWasSet {
// adjust more attributedString properties
}
lableAtt.attributedText = attributedString
lableAtt.isUserInteractionEnabled = true
lableAtt.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapOnLabel(_:))))
@objc func handleTapOnLabel(_ recognizer: UITapGestureRecognizer) {
guard let text = lableAtt.attributedText?.string else {
return
}
if let range = text.range(of:"terms") {
// goToTermsAndConditions()
} else if let range = text.range(of: "Privacy"){
print(range)
UIApplication.shared.open(URL(string: "https://www.google.com/url?q=https://www.iubenda.com/privacy-policy/58446596&sa=D&source=hangouts&ust=1528787597335000&usg=AFQjCNEPkofPxSm7TDRMvxjOjCz5cio27w")!, options: [:])
}
}
推荐阅读
- java - 使用格式化字段进行数学运算
- javascript - 如何读取 Javascript 文件
- azure-ad-b2c - Azure AD B2C 资源所有者密码凭据身份验证
- reactjs - 在 React 中编辑用户信息
- single-sign-on - 如何在不单击登录按钮的情况下首次检查 SSO 会话
- c++ - 有一个线程拥有它运行 C++ 的函子
- python - 如何在 Pandas 中读取多 CSV?
- ios - 如何在没有 segues 的情况下管理多视图应用程序
- c - C-比较两个四位数字数组的函数
- jquery - 如何将 Thymeleaf 消息与 jquery 变量连接起来