Xcode UI Switch Help

Discussion in 'iOS Programming' started by njharris97, Mar 11, 2014.

  1. njharris97 macrumors member

    Hi guys

    I am wanting to create an application in Xcode that has a UI switch, that will comment out a line of code in my view controller.m file. I am assuming this is the best way to do it.

    Basically I need that when the UIswitch is set to off, I would like it to run this line of code, but when the user flicks the switch to the on position, I would that line of code not to be run.

    Any ideas will be much appreciated.
  2. DennisBlah macrumors 6502


    Dec 5, 2013
    The Netherlands
    Just as simple as making an if statement.

    if(myUISegmentedControl.index==1) {
     NSLog(@"The switch is clicked 'on' (to the right) so we are running this script");
    if the switch is to the left (index == 0) the code within the if wont get runned.
  3. waterskier2007 macrumors 68000


    Jun 19, 2007
    Novi, MI
    I think what you are looking for is the "UIControlEventValueChanged" event for UISwitch (really inherited from UIControl). If you hook up your UISwitch to an IBAction with the Value Changed event, it will trigger that IBAction when the switch is flipped. From there you can use what DennisBlah said to check if the switch is on or off
  4. Duncan C macrumors 6502a

    Duncan C

    Jan 21, 2008
    Northern Virginia
    A UISwitch is slightly simpler, since it only has 2 states, on and off, and it has a getter isOn.

    if(mySwitch.isOn) {
     NSLog(@"The switch is on, so we are running this code");
    As the other poster pointed out, you can write an IBAction method and attach it to the valueChanged event for the switch. That way the action will be called every time the user toggles the switch position.

Share This Page