RubberDucky4444 RubberDucky4444 - 6 months ago 39
Swift Question

Swift UISwitch not working first time

I have a UISwitch on my view controller and i have it so when i toggle it the text of a button changes. the first time i toggle it off and on it doesnt work, but if you try it a second time it works...is there something i am missing in my code?

UISwitchOutlet.addTarget(self, action: #selector(MainPageViewController.switchChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)


func switchChanged(mySwitch: UISwitch) {
let value = UISwitchOutlet.on
if value {
self.enterRoom.titleLabel?.text = "Enter Room"
} else {
self.enterRoom.titleLabel?.textAlignment = NSTextAlignment.Center
self.enterRoom.titleLabel?.text = "Create"


}
}

Answer

Try below. Your value would always be on, because you were setting to the switch on state.

func switchChanged(mySwitch: UISwitch) {
    if mySwitch.isOn {
        self.enterRoom.titleLabel?.text = "Enter Room"
    } else {
        self.enterRoom.titleLabel?.textAlignment = NSTextAlignment.Center
        self.enterRoom.titleLabel?.text = "Create"
    }
}
Comments