繁体   English   中英

UITableView 中的 cell.accessoryType 问题

[英]problem in cell.accessoryType in UITableView

在我的应用程序中,如果用户按下 UITableView 中的任何单元格,则单元格的附件类型将设置为复选标记,如下所示

-(void)Check:(UITableView *)tableView Mark:(NSIndexPath *)indexPath  
{  
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;  
     buttonCount++;  
    [selectedCellArray addObject:indexPath];  
} 

如果用户按下相同的单元格,则取消选中将如下所示

-(void)UnCheck:(UITableView *)tableView Mark:(NSIndexPath *)indexPath  
{  
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType =   UITableViewCellAccessoryNone;  
    buttonCount--;    
     if (buttonCount == 0) {    

        [selectedCellArray removeAllObjects];  
    }  
}    

我打电话给这个

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{  
if([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark)
    {  
        [self UnCheck:tableView Mark:indexPath];  
    }  
else  
    {  
        [self Check:tableView Mark:indexPath];

    }

问题是当我按下第一个单元格时,它调用检查方法并将单元格标记为但是当我向下滚动时,我发现还有 2-3 个检查单元格......即使我没有 select 那些单元格......我不知道为什么和它是如何自动检查...
我希望有人知道问题出在哪里非常感谢

因为单元格将被表格视图重用。 还要在tableView:cellForRowAtIndexPath:方法中设置复选标记/附件类型。

是的。我经常看到这种情况。

管理 UITableViewCell state 的正确模式不是直接操作 TableViewCell 来更新 UI,而是始终从 cellForRowAtIndexPath(或 tableView:willDisplayCell:forRowAtIndexPath:)设置、绘制和创建正确的 state

这意味着,如果用户单击单元格并且您需要更新该单元格的 UI,则将该单元格的新 state 存储在数组或字典中(我发现以 NSIndexPath 为键的 NSMutableDictionary 效果很好)。

然后调用 reloadRowsAtIndexPaths:withRowAnimation: 或只是 [tableView reloadData] 以便 cellForRowAtIndexPath 读取该数组或字典并正确绘制单元格。

否则,cellForRowAtIndexPath 将不断覆盖您的更改并使用包含不正确 state 的回收单元。

one exception to this rule would be if you would like a nice animation between the two states... if that is the case, save off your new state, perform your animation right there on the cell, then when the animation completes, call the相同的 reloadRowsAtIndexPaths:withRowAnimation 或 reloadData 以便在新的 state 中重新绘制单元格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM