'How to set the value of checkboxes with a single variable
Hello folks of StackOverflow today I bring forth an optimization problem for you in swift
As shown in the screenshot I have checkboxes in my screen and I have to save their values depending on if they are clicked (if checked its true otherwise its false) as far as my problem concerned I solved the visual part ive connected each button to a single event handler and changed their images depending on the click as shown below
@IBAction func checkBtnpressed(_ sender: UIButton) {
if sender.image(for: .normal) == UIImage(named: "imgCheckSelected") {
sender.setImage(UIImage(named: "ImgcheckBox"), for: .normal)
}else{
sender.setImage(UIImage(named: "imgCheckSelected"), for: .normal)
}
}
but I couldn't figure a way out for setting their true and false values and I don't want to define 15 separate values so my question is can I solve this with only one boolean value can I use sender to set each button true or false depending on the times clicked or anything else. Please help me find a solution
Solution 1:[1]
Your every defined button can hold the state of your checkbox. You need to use normal and selected state of your button.
private lazy var btnClick:UIButton = {
var btn = UIButton()
btn.setImage(UIImage(named: "ImgcheckBox"), for: .normal)
btn.setImage(UIImage(named: "imgCheckSelected"), for: .selected)
btn.addTarget(self, action: #selector(self. checkBtnpressed(btn:)), for: .touchUpInside)
return btn
}()
@objc func checkBtnpressed(btn: UIButton) {
btn.isSelected = !btn.isSelected
}
Now when you need all the selected checkboxes, Just iterate through your buttons and pick the values whose isSelected property is true.
Solution 2:[2]
A UIButton has several states it can be in. You have discovered one of them .normal
. Another state that a button can be in is .selected
. Therefore, you can set the image for the selected state as UIImage(named: "imgCheckSelected")
and the image for the normal state as UIImage(named: "ImgcheckBox")
.
Once you do that, in your checkBtnpressed(_:)
method, all you have to do is change the state of the button. Later, you can query the state of the button to figure out if it's selected or not.
That said, you really should represent your state in some sort of model object which would either have 15 Bools in it, or have an array of Bools. Don't use your view state as your model.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kishan Raiyani |
Solution 2 | Daniel T. |