UISwitch performing action on value change-iphone sdk
I have a UISwitch
and I need to load the value in a string into an array when change the switch state change to OFF to ON. I have used the following code, but not working.
-(IBAction)toggleSwitch1:(id)sender {
if (addSwitch.on) {
[addSwitch addTarget:self action:@selector(addName:) forControlEvents:UIControlEventValueChanged];
NSLog(@"%@",userName);
}else {
NSLog(@"No");
}
}
-(void)addName:(UIControl*)sender {
[alertList开发者_如何学运维 addObject:userName];
NSLog(@"AlertList: %@", alertList);
}
And if once the state changed to ON, how can I remain the same state, if I reload the page?
Please share your thoughts. Thanks
In viewDidLoad
use this one:
-(void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
if([userdefault boolForKey:@"yes"]) {
addSwitch.on=YES;
} else {
addSwitch.on=NO;
}
}
-(IBAction)toggleSwitch1:(id)sender
{
NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
if (addSwitch.on) {
[self performSelector:@selector(addName:) withObject:userName];
NSLog(@"%@",userName);
[userdefault setBool:YES forKey:@"yes"];
} else {
[userdefault setBool:NO forKey:@"no"];
NSLog(@"No");
}
}
-(void)addName:(UIControl*)sender
{
[alertList addObject:sender];
NSLog(@"AlertList: %@", alertList);
}
Looks like the issue you're having is that the toggleSwitch method is called when the state changes and then it starts listening for the change using the addTarget: method. You should choose one or the other to handle the change.
-(IBAction)toggleSwitch1:(id)sender{
if (addSwitch.on) {
[self addName:userName];
} else {
//do something else
}
}
-(void)addName:(UIControl*)sender{
[alertList addObject:userName];
}
To save the switch state just have another variable that stores the switch state and call the setOn:animated: method in viewDidLoad.
精彩评论