在tableview中保存复选框按钮

时间:2013-11-05 11:18:44

标签: save tableview nsuserdefaults

我正在使用Storybord,我得到了一个带有复选框按钮的tableview。

我正在使用NSUserDefaults保存我的复选框按钮的状态我试图用Core Data保存它但我不知道如何更好地去NSUserDefaults的简单方法。

并且checkboxbutton工作正常,但问题是它没有保存checkboxbutton的状态!

当我关闭应用并再次打开它时,它未保存。

任何人都可以帮助我,我尽力解决这个问题,但没有运气

这是我的代码

@property (strong, nonatomic) IBOutlet UIButton *myButton;

@property (nonatomic,assign) BOOL checked;


  @synthesize myButton,checked;


 - (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
checked = [defaults boolForKey:@"boxIsChecked"];
[defaults synchronize];
[self checkTheBox];

}

   - (UITableViewCell *)tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath  *)indexPath
    {
   static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = 
  [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...
NSManagedObject *device = [self.Work objectAtIndex:indexPath.row];

[cell.textLabel setText= [Work valueForKey:@"name"]



myButton = [UIButton buttonWithType:UIButtonTypeCustom] ;
[myButton setFrame:CGRectMake(260,2,40,40)];
myButton.tag = indexPath.row;
[myButton setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(ButtonCheckMark:) 
forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:myButton];
cell.selectionStyle = UITableViewCellSelectionStyleNone;


return cell;
}


- (IBAction)ButtonCheckMark:(id)sender {

myButton = (UIButton *)sender;
NSLog(@"playButton %li" , (long)myButton.tag);

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

if (!checked) {
    [myButton setImage:
    [UIImage imageNamed:@"checkBoxMarked.png"]  forState:UIControlStateNormal];
    checked = YES;
    [defaults setBool:checked forKey:@"boxIsChecked"];
}

else if (checked) {
    [myButton setImage:
   [UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
    checked = NO;
    [defaults setBool:checked forKey:@"boxIsChecked"];
  }

[defaults synchronize];

   }
 - (void) checkTheBox {
if (!checked) {
    [myButton setImage:
  [UIImage imageNamed:@"checkBox.png"]   forState:UIControlStateNormal];
   }

else if (checked) {

    [myButton setImage:
  [UIImage imageNamed:@"checkBoxMarked.png"]   forState:UIControlStateNormal];
   }
   }

0 个答案:

没有答案