如果选中复选框,我想保存值TRUE,如果在数组中取消选中则保持FALSE,我该怎么做。我在tableview中实现了复选框。代码是,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BOOL checked = [[checkedArr objectAtIndex:indexPath.row] boolValue];
[checkedArr removeObjectAtIndex:indexPath.row];
[cheval insertObject:(checked) ? @"FALSE":@"TRUE" atIndex:indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:@"tick.png"] : [UIImage imageNamed:@"white_bg.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
cell.accessoryView=button;
}
答案 0 :(得分:0)
[cheval insertObject:(checked) ? @"FALSE":@"TRUE" atIndex:indexPath.row];
这会向cheval
数组添加值的字符串表示形式。您可以将其更改为:
[cheval insertObject:@(checked) atIndex:indexPath.row];
要将字符串更改为NSNumber
(以便您可以在其上调用boolValue
)。
答案 1 :(得分:0)
试试这个:
[array2 insertObject:[NSNumber numberWithBool:[checkButton state]] atIndex:indexPath.row];
checkButton是复选框的出口。
答案 2 :(得分:0)
NSMutableArray与C数组不同。它更像是一个列表。所以
BOOL checked = [[checkedArr objectAtIndex:indexPath.row] boolValue]; [checkedArr removeObjectAtIndex:indexPath.row];
不会像你想要的那样工作。
[cheval insertObject:(checked) ? @"FALSE":@"TRUE" atIndex:indexPath.row];
包含的对象少于cheval
,则indexPath.row
也会崩溃。我建议使用NSMutableDictionary
代替NSMutableArray
。您可以使用NSIndexPath
对象作为键。并改变一点算法:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *indexPathKey = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]; // we use this code because in iOS 7 indexPath has type UIMutableIndexPath
BOOL checked = ![checkedDict[indexPathKey] boolValue];
checkedDict[indexPathKey] = @(checked);
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:@"tick.png"] : [UIImage imageNamed:@"white_bg.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
cell.accessoryView=button;
}
另外,为什么不使用默认选中标记。如果您使用它,您应该通过以下方式更改您的代码:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *indexPathKey = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]; // we use this code because in iOS 7 indexPath has type UIMutableIndexPath
BOOL checked = ![checkedDict[indexPathKey] boolValue];
checkedDict[indexPathKey] = @(checked);
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = checked ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
}