最后我做了以下内;
为我的实际复选框创建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
就像它可以在网页上工作 - 点击“标签”也会标记复选框 - 除非用户点击了可以打开链接/操作的“条款和条件”。 –