【问题标题】:Doesn't work UITableViewCell's method不起作用 UITableViewCell 的方法
【发布时间】:2013-01-10 20:32:50
【问题描述】:

当我做简单的 HelloWorld 应用程序时,我遇到了问题

[self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic]

,这个方法不起作用……我不知道为什么?请帮忙

代码:

- (void)viewDidLoad
{
int i = 0;
[super viewDidLoad];
    while (i < 10 ) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
        i++;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
   cell.textLabel.text = @"HelloWorld";
   return cell;
}

应用应创建 10 个带有标签 @"HelloWorld"

的单元格

【问题讨论】:

标签: ios objective-c


【解决方案1】:

你做错了。如果你想要 10 个单元格,你不应该一次添加一个,你应该在 numberOfRowsInSection 中返回 10,例如:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

此外,单元格中不会显示任何内容,因为您在 cellForRowAtIndexPath 中的单元格上调用了 alloc/init。像这样修改你的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text = @"HelloWorld";
    return cell;
}

【讨论】:

  • [self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic] 不做 tableView:cellForRowAtIndexPath...
  • @EarthUser 我认为您在这里忽略了重点。如果numberOfRowsInSection 返回 1,则表格将只有 1 个单元格。如果您的问题是从未调用过cellForRowAtIndexPath,那么您的表格视图的委托/数据源设置不正确。
  • @EarthUser 抱歉,由于您已将我的答案标记为正确,我认为您解决了问题,并且我在您的屏幕截图中看到您返回 0 个部分。尝试将其更改为返回 1。
  • 非常感谢这篇文章!!!!=) 我发现了问题,问题出在 CellIdentifier 上:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-14
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多