Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of UIButtons in Swift 4

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?

like image 371
Daniel G Avatar asked Oct 15 '25 14:10

Daniel G


1 Answers

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).

  • Create one IBAction and connect all buttons to the action
  • Use 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
        }
    }
    
like image 170
vadian Avatar answered Oct 17 '25 04:10

vadian