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
2
Answers
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 asUIImage(named: "imgCheckSelected")
and the image for the normal state asUIImage(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.
Your every defined button can hold the state of your checkbox.
You need to use normal and selected state of your button.
Now when you need all the selected checkboxes, Just iterate through your buttons and pick the values whose isSelected property is true.