为了创建它,我使用了一个带有 NSMutableAttributedString
的 UIButton 控件来为“条款和条件”提供与其余文本不同的样式。
就像网页上的复选框一样,我希望用户能够点击灰色文本或图像本身来打开或关闭复选框。
但如果用户点击“条款和条件”,我希望它执行一个操作(例如加载条款 URL)。
这在 Android 中很容易做到,因为您可以使用 checkbox.setMovementMethod(LinkMovementMethod.getInstance());
,但在 iOS 中,我真的很难找到一种方法来基本创建一个带有包含链接的标签的复选框。
以前有没有人这样做过,您是如何处理的?
最佳答案
我最终做了以下事情;
为我的实际复选框创建了一个 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 的非链接文本都会打开和关闭复选框。 “条款和条件”文本将链接到网站或其他地方。
希望这可以帮助其他人。
关于ios - UIButton 标签检测点击特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44390143/