【发布时间】:2019-04-20 19:38:58
【问题描述】:
我以编程方式在我的 tableViewController 第 3 行添加了一个 uiswitch。它正在正确显示,我将开关的状态保存在 NSUserDefaults 中。我也在比较,取决于 NSUserDefaults 值和字符串值,我试图将我的开关状态更改为(打开或关闭)但问题是开关的状态没有改变。
这是我的代码:
- (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 值进行比较,并尝试更改开关的状态。正常进入断点,但不会将开关的状态从ON变为OFF。
【问题讨论】:
标签: iphone objective-c