gpt4 book ai didi

ios - 设置 CheckBox 开 - 关

转载 作者:行者123 更新时间:2023-11-28 08:31:54 25 4
gpt4 key购买 nike

我通过创建一个 UIButton 类创建了一个带有按钮的自定义复选框这是类(class)

import UIKit

class CheckBox: UIButton {
// Images
let checkedImage = UIImage(named: "ic_check_box")! as UIImage
let uncheckedImage = UIImage(named: "ic_check_box_outline_blank")! as UIImage

// Bool property
var isChecked: Bool = false {
didSet{
if isChecked == true {
self.setImage(checkedImage, forState: .Normal)
} else {
self.setImage(uncheckedImage, forState: .Normal)
}
}
}

override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}

func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
}
}
}

我在 viewcontroller 中有两个复选框,但我不知道如何在 ViewController.class 中设置复选框以在选中复选框“Si”时执行操作,复选框“No”设置为未选中,如图中所示

Checkbox Si

Checkbox No

最佳答案

您的 CheckBox 类应该采用委托(delegate)模式,以便它可以通知其委托(delegate)(在本例中是您的 View Controller )其值已更改。然后在您的 View Controller 中,您可以根据需要更新另一个复选框:

protocol CheckBoxDelegate {
func checkBoxDidChange(checkbox: CheckBox) -> Void
}

class CheckBox: UIButton {
// Images
let checkedImage = UIImage(named: "ic_check_box")! as UIImage
let uncheckedImage = UIImage(named: "ic_check_box_outline_blank")! as UIImage

weak var delegate: CheckBoxDelegate?
// Bool property
var isChecked: Bool = false {
didSet{
if isChecked == true {
self.setImage(checkedImage, forState: .Normal)
} else {
self.setImage(uncheckedImage, forState: .Normal)
}
}
}

override func awakeFromNib() {
self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}

func buttonClicked(sender: UIButton) {
isChecked = !isChecked
self.delegate?.checkBoxDidChange(self)
}
}

然后,在您的 View Controller 中:

class ViewController: UIViewController, CheckBoxDelegate {

@IBOutlet var siCheckBox: CheckBox! // Initialise some other way if you aren't using storyboard/nib
@IBOutlet var noCheckBox: CheckBox!

override func viewDidLoad() {
super.viewDidLoad()

self.siCheckBox.delegate = self
self.noCheckBox.delegate = self
}

//Mark: CheckBoxDelegate

func checkBoxDidChange(checkbox: CheckBox) {
if checkbox == self.siCheckBox {
self.noCheckBox.isChecked = !checkbox.isChecked
} else {
self.siCheckBox.isChecked = !checkbox.isChecked
}
}

从用户体验的角度来看,我会质疑为什么需要两个复选框。复选框是一个开/关控件,因此您通常会看到“选择非常好的选项?”之类的文本。带有一个用于是/否的复选框;选中是,未选中是否。

关于ios - 设置 CheckBox 开 - 关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38690390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com