I’ve set a switch on my overlay, which appears every time my app launches the camera. The switch appears, which is fine. But how do I create the if conditions to command the switch to perform an action when on or off?
//This is the overlay.
- (UIView*)CommomOverlay {
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake (30,400,20,20)];
[mySwitch addTarget:self action:@selector(mySwitch)
forControlEvents:UIControlEventAllTouchEvents];
[view addSubview:mySwitch];
return view;
}
So the switch appears on the overlay, but how do I command it do something when called?
I’ve tried the following
-(void)mySwitch {
if ([mySwitch.on]){
execute this..
}
}
But the above doesn’t work. I get an error saying “undeclared identifier, did you mean UISwitch?”. So then I replace mySwitch.on with UISwitch.on, then it says ” property on not found on object of type UISwitch”.
I just want to execute my if else method properly. I made the overlay, I made the switch code and it appears on the overly perfectly. But now I want it to do something with an if/else condition. How do I rectify this?
What did I do wrong?
Glad you decided on the UISwitch, its a much more straightforward solution in my opinion. As for what your problem is, its related to scoping. You are declaring your UISwitch in your overlay initialization, and then the function ends, and you lose the ability to access your UISwitch.
What you’ll need to do is create a property for it in your .h, then just set it equal to your property inside of your overlay initialization. That should fix your problem.
EDIT: Going through the problems you mentioned in the comment:
1) I believe that your declartion should be,
Afterwards, you will need to do a
@synthesize mySwitch;in your .m file2) The reason for this is because you have 2 variables with the same name since it seems that you are redeclaring mySwitch in a few places. I’m guessing these places your code looks like:
It should just look like:
The reason being that you have already declared it in your .h file, you simply need to initialize or manipulate it. If you declare it once again, you will be overwriting it with a new instance that will once again not exist after you exit your function.
3) You dont need to set mySwitch = mySwitch for the synthesize, see my above code. Also make sure that your function name is not the same as your variable name!
Feel free to comment with updates and more questions.
-Karoly