我已经以编程方式在我的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。
发布于 2013-05-28 02:37:11
您可以关闭UISwitch设置
[yourSwitch setOn:NO animated:YES]; 并打开设置
[yourSwitch setOn:YES animated:YES];发布于 2011-10-14 17:59:18
通过设置以下内容,您可以简单地将交换机设置为ON:
switchOutlet.on = YES;并通过以下方式将其设为OFF:
switchOutlet.on = NO;发布于 2013-05-28 02:45:36
这没有任何意义:
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];https://stackoverflow.com/questions/7765945
复制相似问题