I've made a series of checkboxes in UiKit with UIButtons:
@IBOutlet weak var Box1: UIButton!
@IBOutlet weak var Box2: UIButton!
@IBOutlet weak var Box3: UIButton!
....
@IBOutlet weak var Box59: UIButton!
// Gives the button an action
@IBAction func Box1(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
@IBAction func Box2(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
@IBAction func Box3(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
....
@IBAction func Box59(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
// Creates button images of checkbox and unchecked box
var BoxON = UIImage(named: "CheckBox")
var BoxOFF = UIImage(named:"UnCheckBox")
// Allows the button to be set to the image, if selected or not
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Box1.setImage(BoxOFF, for: .normal)
Box1.setImage(BoxON, for: .selected)
Box2.setImage(BoxOFF, for: .normal)
Box2.setImage(BoxON, for: .selected)
Box3.setImage(BoxOFF, for: .normal)
Box3.setImage(BoxON, for: .selected)
....
Box59.setImage(BoxOFF, for: .normal)
Box59.setImage(BoxON, for: .selected)
}
This is all the code necessary to make as many checkboxes as possible. However, each checkbox requires creating/moving a button to the right spot on the storyboard, linking the button from the storyboard to the button variable that was just coded. This can take a lot of time since I need over 100 buttons per view controller.
Is there a faster way to do this by making an array of buttons? or something similar?
It is possible to declare an IBOutlet
as array
Create an IBOutlet
as array
@IBOutlet var boxes : [UIButton]!
Connect all buttons to the same outlet (in the desired order)
In viewDidAppear
use a loop or forEach
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
boxes.forEach {
$0.setImage(BoxOFF, for: .normal)
$0.setImage(BoxON, for: .selected)
}
}
Add unique tags to the buttons (optional).
IBAction
and connect all buttons to the actionUse a switch statement to distinguish the buttons by index in the array or by tag
@IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
let index = boxes.index(of: sender)!
switch index {
// handle the cases
}
}
@IBAction func boxTouched(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
switch sender.tag {
// handle the cases
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With