最後我做了以下內;
爲我的實際複選框創建UIButton(空文本標籤),爲我的相鄰複選框標籤文本創建一個UITextView。
然後我用NSMutableAttributedString
這樣;
class MyViewController: UIViewController, UITextViewDelegate {
override func viewDidLoad() {
let attributedTermsTitle = NSMutableAttributedString()
attributedTermsTitle.append(NSAttributedString(string: "I have read and accept the ", attributes: [NSFontAttributeName:UIFont(name: "My-Font", size: 14)!]))
attributedTermsTitle.append(NSAttributedString(string: "Terms & Conditions", attributes: [NSFontAttributeName:UIFont(name: "My-Font", size: 14)!, NSLinkAttributeName: "terms"]))
termsText.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.blue]
termsText.attributedText = attributedTermsTitle
termsText.delegate = self
termsText.isSelectable = true
termsText.isUserInteractionEnabled = true
termsText.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MyViewController.toggleCheckbox)))
}
func toggleCheckbox(sender: UITapGestureRecognizer) {
termsButton.isChecked = !termsButton.isChecked
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
let link = URL.absoluteString
if(link == "terms") {
// link to the Terms web page/screen
}
return false
}
}
,爲UIButton的,居然給班上的;
class CheckBox: UIButton {
let checkedImage = UIImage(named: "checkbox_on")! as UIImage
let uncheckedImage = UIImage(named: "checkbox_off")! as UIImage
var isChecked: Bool = false {
didSet{
if isChecked == true {
self.setImage(checkedImage, for: UIControlState.normal)
} else {
self.setImage(uncheckedImage, for: UIControlState.normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControlEvents.touchUpInside)
self.isChecked = false
}
func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
}
}
}
最終結果是,UIButton和UITextView的非鏈接文本都會打開和關閉複選框。 「條款&條款」文本將鏈接到網站或在其他地方繼續。
希望這可以幫助別人。
此鏈接可幫助您。 https://stackoverflow.com/questions/20541676/ios-uitextview-or-uilabel-with-clickable-links-to-actions –
你想點擊標籤或當開關改變? – Gregga17
就像它可以在網頁上工作 - 點擊「標籤」也會標記複選框 - 除非用戶點擊了可以打開鏈接/操作的「條款和條件」。 –