【问题标题】:tableview won't update after adding objects to an array将对象添加到数组后,tableview 不会更新
【发布时间】:2012-01-13 21:10:56
【问题描述】:

我的主视图中的弹出框内有一个表格视图,它是一个网络浏览器。每当用户访问一个网页时,我希望它将该页面添加到最近访问过的网站列表中。我设置了代码以将 URL 作为字符串添加到作为表格视图的数据源的数组中。表格视图仅显示访问的第一个站点,并且不会显示任何内容。但是我知道这些站点正在添加到数组中,因为该数组在添加后使用 NSLog 语句显示站点。但是它们仍然不会出现在表格中。谁能帮帮我?

编辑:

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [recentlyVisitedUrls count];
}

【问题讨论】:

  • 你在打电话给[tableView reloadData]吗?
  • 是的,但它会删除以前存在的数据

标签: objective-c ios uitableview nsarray


【解决方案1】:

还要确保从 – tableView:numberOfRowsInSection: 返回数组的正确长度

【讨论】:

    【解决方案2】:

    试试

    [tableView reloadTable];
    

    添加新数据后。

    【讨论】:

    • 当我这样做时,我必须在添加数据之前放置它,它会显示为 [tableView reloadData];之前存在的数据也会消失
    • 显示 numberOfSectionsInTableView:、numberOfRowsInSection: 和 cellForRowAtIndexPath: 的委托方法。输入您的原始问题以进行格式化。
    • 我已修复它。更新 numberOfRowsInSection 后,我不得不再次重新加载数据:
    【解决方案3】:

    如果你不想动画更新,你可以调用:

    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]

    如果你需要动画,最好阅读:Table View Programming Guide for iOS,你需要Batch insert…部分。

    【讨论】:

      【解决方案4】:

      如果您有一张大桌子,[tableView reloadData] 可能并不理想。它还将您的视图重置到表格的开头,这可能是可取的,也可能不是可取的。你可以试试这样的:

      NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_model.recordCount - 1 inSection:0];
      [_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
      [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
      

      顺便说一句,_model 是示例中表的数据委托类。

      此外,请确保数据委托在您插入之前正确更新其总数,否则您的应用将在 insertRowsAtIndexPaths 上崩溃。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-14
        • 1970-01-01
        • 2022-10-06
        • 2022-01-16
        相关资源
        最近更新 更多