Selected segment of UISegmentedControl
I开发者_高级运维 am using an UISegmentedControl with two sections: the first is Don't Remember Password and the second is Remember Password. If they select Remember Password, I use NSUserDefaults to remember this. On startup, how do I make Remember Password selected if NSUserDefaults is YES?
if ([[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Remember password"] == YES)
{
//Make the second segment (segment 1 as it would be called, since first is segment 0) selected
}
It is as simple as setting selectedSegmentIndex inside of viewDidLoad to ensure that the segment is not nil.
-(void)viewDidLoad
{
[super viewDidLoad];
if([[NSUserDefaults standardUserDefaults] boolForKey:@"Remember Password"])
{
segment.selectedSegmentIndex = 1;
}
else
{
segment.selectedSegmentIndex = 0;
}
}
Also why not use a UISwitch
and set the on
value directly to the stored value?
When dealing with a boolean setting I would recommend using a UISwitch instead of a segmented control. The switch would either activate or de-activate the remember password.
The way you set the value is correct, to get the value back you use:
[[NSUserDefaults standardUserDefaults] boolForKey:@"Remember password"];
So if you use a UISwitch you could do:
switch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"Remember password"];
If you do want to use a UISegmentedControl it is a bit longer but just as simple:
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"Remember password"]) {
segmentedControl.selectedSegmentIndex = 1;
}
else{
segmentedControl.selectedSegmentIndex = 0;
}
Just remember that a UISwitch makes more senese to the user when dealing with a boolean setting.
Update:
To set the value using a switch you simply do:
[[NSUserDefaults standardUserDefaults] setBool:switch.on forKey:@"Remember password"];
It is a lot simpler than using a UISegmentedControl.
精彩评论