我通过一个UIButton类创建了一个带按钮的自定义复选框 这是班级
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中有两个复选框,但我不知道如何在CheckController.class中设置复选框,当复选checkBox“Si”时,复选框“No”设置为未选中,如图所示
答案 0 :(得分:0)
我会将func buttonClicked(sender: UIButton)
移动到父ViewController。
let siCheckBox = CheckBox()
let noCheckBox = CheckBox()
func checkBoxToggled(sender: AnyObject) {
noCheckbox.isChecked = !noCheckbox.isChecked
siCheckbox.isChecked = !siCheckbox.isChecked
}
只有在您确定始终至少检查到1时,这才是安全的。否则,我会添加一个if
语句,以确保在l处被检查。
答案 1 :(得分:0)
您的CheckBox
类应该采用委托模式,以便它可以告知其代理(在本例中是您的视图控制器)其值已更改。然后在视图控制器中,您可以根据需要更新另一个复选框:
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
}
}
从用户体验的角度来看,我会问为什么你需要这两个复选框。复选框是一个开/关控件,所以你通常会有“选择真的很棒的选项?”这样的文字。带有一个是/否的复选框;选中是,未选中是否。