我已经以编程方式在tableViewController第3行添加了一个uiswitch。它正在正确显示,我正在NSUserDefaults中保存交换机的状态。我也在比较,根据NSUserDefaults值和字符串值我试图将我的开关状态改为(ON或OFF)但问题是开关状态没有改变。
这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
switch (indexPath.row) {
case 2:
cell.textLabel.text = @"Weather";
switchControl = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchControl;
[self.switchControl setOn:YES animated:NO];
[self.switchControl addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[switchControl release];
break;
default:
break;
}
cell.textLabel.text = [settings objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(void)switchChanged:(id)sender
{
app= (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
NSString *value;
userdefaults = [NSUserDefaults standardUserDefaults];
if(!switchControl.on){
value = @"OFF";
[userdefaults setObject:value forKey:@"stateOfSwitch"];
}
[userdefaults setObject:value forKey:@"stateOfSwitch"];
[userdefaults synchronize];
}
- (void)viewWillAppear:(BOOL)animated {
NSString *_value= [[NSUserDefaults standardUserDefaults] stringForKey:@"stateOfSwitch"];
if([_value compare:@"ON"] == NSOrderedSame){
[self.switchControl setEnabled:YES];
}
else {
[self.switchControl setEnabled:NO];
}
[super viewWillAppear:animated];
}
在视图中WillAppear我将字符串与我的NSUserDefaults值进行比较并尝试更改switch的状态。它正确地进入断点,但不会将开关状态从ON更改为OFF。
答案 0 :(得分:6)
您可以关闭UISwitch设置
[yourSwitch setOn:NO animated:YES];
并启用设置
[yourSwitch setOn:YES animated:YES];
答案 1 :(得分:0)
您可以通过设置:
来简单地切换ON
switchOutlet.on = YES;
并通过以下方式使其成为OFF
switchOutlet.on = NO;
答案 2 :(得分:0)
这没有任何意义:
switchControl = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchControl;
[self.switchControl setOn:YES animated:NO];
[self.switchControl addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[switchControl release];
你创建一个开关,做一些东西,大概是另一个开关,然后释放第一个。试试这个:
self.switchControl = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchControl;
[self.switchControl setOn:YES animated:NO];
[self.switchControl addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
答案 3 :(得分:0)
尝试在cellForRowAtIndexPath
而不是viewWillAppear
中编写以下代码:
NSString *_value= [[NSUserDefaults standardUserDefaults] stringForKey:@"stateOfSwitch"];
if([_value compare:@"ON"] == NSOrderedSame) {
[self.switchControl setEnabled:YES];
} else {
[self.switchControl setEnabled:NO];
}