我正在开发一个使用表格 View 的 ToDoList iOS 应用程序。单元格内容(UITableCellView)由 nsmutablearray 的实例变量填充。
当我添加一个新的 ToDoItem 时,我添加的每一行的内容都会显示两次。当我放置断点并调试代码时,我发现 cellForRowAtIndexPath 方法为我添加的每一行调用两次。为什么会这样。如何处理这种情况,或者是否有任何其他替代方法可以返回 UITableCellView 单元格进行显示。
方法如下图
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell;
cell = [self.tableView dequeueReusableCellWithIdentifier:@"ListPrototypeCell" forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ListPrototypeCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
ToDoItem *item = [self.toDoItems objectAtIndex:indexPath.row];
cell.textLabel.text = item.itemName;
return cell;
}
当用户添加新项目时调用此方法
-(IBAction)unwindToList:(UIStoryboardSegue *)segue{
AddToDoItemViewController *ITEM = [segue sourceViewController];
ToDoItem *tItem = ITEM.toDoItem;
if (tItem!=nil) {
[self.toDoItems addObject:tItem];
[self.tableView reloadData];
[self setItems:self.toDoItems];
}
}
编辑:
-(void)setItems:(NSMutableArray *)item{
if (item!=nil) {
tDItems = item;
}
}
tDItems 只是我正在使用的另一个实例变量
提前致谢
最佳答案
如果重复的项目被添加到数组中,只需检查你的数组,因为即使 cellForRowAtIndexPath 被调用两次,如果数组中的项目不重复,它也不会创建重复的单元格。由于多次重新加载,cellForRowAtIndexPath 可能会被调用两次
关于ios - cellForRowAtIndexPath 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167797/