tableview iOS Objective-C中的多个复选框



我在tableview的多个复选框功能工作,我必须在谷歌搜索,最后我得到了一个解决方案。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if ([selectedRowsArray containsObject:[contentArray objectAtIndex:indexPath.row]]) {
    cell.imageView.image = [UIImage imageNamed:@"checked.png"];
}
else {
   cell.imageView.image = [UIImage imageNamed:@"unchecked.png"];
}
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleChecking:)];
[cell.imageView addGestureRecognizer:tap];
cell.imageView.userInteractionEnabled = YES; //added based on @John 's comment
//[tap release];
cell.textLabel.text = [contentArray objectAtIndex:indexPath.row];
return cell;
}
- (void) handleChecking:(UITapGestureRecognizer *)tapRecognizer {
CGPoint tapLocation = [tapRecognizer locationInView:self.tableView];
NSIndexPath *tappedIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation];
if ([selectedRowsArray containsObject:[contentArray objectAtIndex:tappedIndexPath.row]]) {
    [selectedRowsArray removeObject:[contentArray objectAtIndex:tappedIndexPath.row]];
}
else {
    [selectedRowsArray addObject:[contentArray objectAtIndex:tappedIndexPath.row]];
}
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:tappedIndexPath] withRowAnimation: UITableViewRowAnimationFade];
}

在代码中我有一个疑问。什么是selectedRowsArray,什么是ContentArray请解释一下。

selectedRowsArray是在contentArray旁边维护的另一个数组,用于保存当前在UITableView中选择的单元格的内容。contentArray保存填充单元格的实际内容。

注意以下几行:

if ([selectedRowsArray containsObject:[contentArray objectAtIndex:indexPath.row]]) 
{
    cell.imageView.image = [UIImage imageNamed:@"checked.png"];
}
else 
{
   cell.imageView.image = [UIImage imageNamed:@"unchecked.png"];
}

检查单元格内容是否存在于selectedRowsArray中,这意味着单元格已被选中。

选择和取消选择是由handleChecking:方法处理的,它将对象从contentArray中的相同索引添加或删除到selectedRowsArray中。

您现在必须理解UITableView中的单元格是重用的,因此内存中UITableViewCell的实际数量很可能少于UITableView中显示的单元格数量。因此,需要一个系统,它可以实际确定单元格当前是否被选中,以便在视图中再次呈现单元格时填充此状态。

实现相同目的的其他方法包括在表示每个单元格状态的数组中使用布尔值,或者简单地使用数组中每个选定单元格的索引。

最新更新