Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

njharris97

macrumors member
Original poster
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.
 

DennisBlah

macrumors 6502
Dec 5, 2013
485
2
The Netherlands
Just as simple as making an if statement.

Code:
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.
 

waterskier2007

macrumors 68000
Jun 19, 2007
1,871
228
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
 

Duncan C

macrumors 6502a
Jan 21, 2008
853
0
Northern Virginia
Just as simple as making an if statement.

Code:
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.

A UISwitch is slightly simpler, since it only has 2 states, on and off, and it has a getter isOn.

Code:
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.