Swift&UILabel:我们如何使条款和条件的内联可点击文本



我想为我的条款和条件创建可点击的文本。但它有两个部分如下:

如果继续,则表示您同意服务条款和隐私政策。

我试着用这个方法,但它给了我一个错误的答案。这意味着,如果我点击服务条款,它会打印Privacy Policy或只是在某个地方。

@objc func tapLabel(_ gesture:UITapGestureRecognizer){
guard let text = instructionLabel.text else { return }
print("gesture : (gesture)")

let range1 = (text as NSString).range(of: "the Terms of Service")
let range2 = (text as NSString).range(of: " and ")
let range3 = (text as NSString).range(of: "Privacy Policy")
if gesture.didTapAttributedTextInLabel(label: instructionLabel, inRange: range1) {
print("the Terms of Service")
} else if gesture.didTapAttributedTextInLabel(label: instructionLabel, inRange: range2) {
print(" and ")
} else if gesture.didTapAttributedTextInLabel(label: instructionLabel, inRange: range3){
print("Privacy Policy")
} else {
print("Somewhere else")
}
}

我期待着你的来信。非常感谢。

尝试使用UITextView。

@IBOutlet weak var agreementTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
agreementTextView.delegate = self
agreementTextView.addHyperLinksToText(originalText: "By continuing, you are agreed to the Terms of Service and Privacy Policy.", hyperLinks: [" the Terms of Service" : "SOME_URL", "Privacy Policy." : "OTHER_URL"])
}
extension UITextView {
func addHyperLinksToText(originalText: String, hyperLinks: [String: String]) {
let style = NSMutableParagraphStyle()
style.alignment = .left
let attributedOriginalText = NSMutableAttributedString(string: originalText)
for (hyperLink, urlString) in hyperLinks {
let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
let fullRange = NSRange(location: 0, length: attributedOriginalText.length)
attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Gotham Pro", size: 12)!, range: fullRange)
}
self.linkTextAttributes = [
NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.1960784346, green: 0.3411764801, blue: 0.1019607857, alpha: 1),
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
]
self.attributedText = attributedOriginalText
}
}

最新更新