Using values from array to set states of multiple UISwithces

444 views Asked by At

I have created an array pisteet() that stores the states of nine UISwitches. For off 0 and for on 1. Array pisteet() is global so when I pop out of the page where the switches are, the values are stored in the array but on re-entry, the switches are all set to default which is OFF. So I have a situation where the visual switch and pisteet() array -value do not match.

So I added setSwitchesOnViewLoad() function to my viewDidLoad override func:

    func setSwitchesOnViewLoad() {
    if pisteet[0] == 1 {
        swHTA.setOn(true, animated: false)
    }
    if pisteet[1] == 1 {
        swMunu.setOn(true, animated: false)
    }
    if pisteet[2] == 1 {
        swMaksa.setOn(true, animated: false)
    }
    if pisteet[3] == 1 {
        swStroke.setOn(true, animated: false)
    }
    if pisteet[4] == 1 {
        swVuoto.setOn(true, animated: false)
    }
    if pisteet[5] == 1 {
        swINR.setOn(true, animated: false)
    }
    if pisteet[6] == 1 {
        swAge.setOn(true, animated: false)
    }
    if pisteet[7] == 1 {
        swDrug.setOn(true, animated: false)
    }
    if pisteet[8] == 1 {
        swAlco.setOn(true, animated: false)
    }
}

This works but if I had 100 switches, it would be quite cumbersome to work them like this.

I researched tag's to have each UISwitch an unique tag from 1...9 and then loop through the array and use the index and value to set each UISwitch state. Didn't find anything that I could have used.

Any ideas?

1

There are 1 answers

1
zisoft On BEST ANSWER

Put your switches in an array, too. If you have your viewController designed in InterfaceBuilder, ctrl-drag them all in an OutletCollection, so you will have:

class MyViewController: UIViewController {
    @IBOutlet var switches: [UISwitch]!

    override func viewDidLoad() {
        super.viewDidLoad()

        for var i = 0; i < pisteet.count; ++i {
            self.switches[i].on = pisteet[i] == 1
        }
    }
}