ios - cellForRowAtIndexPath 调用

标签 ios uitableview

我正在开发一个使用表格 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/

相关文章:

ios - 使用两个独立的 View Controller 更新核心数据模型

uitableview - self.tableView 不被识别为 UITableView,而是一个随机方法

ios - 我可以在原型(prototype) UITableViewCell 中使用容器 View 吗

IOS GameKit - 有没有办法通过 "findMatchForRequest"强制创建全新的回合制比赛?

ios - 使用推送通知配置文件安装应用程序失败

ios - 我在使用 npm run ios 命令时遇到错误

ios - 选择单元格 iOS swift 时的复选框功能

ios - dequeueReusableCellWithIdentifier : returns nil even after creating cell instance

ios - 处理游戏进入后台

ios - 如何在 Swift 3 中为 UIView 提供底部阴影?