首页 文章

UITableView不会重复使用故事板的单元格

提问于
浏览
0

我在故事板中发现了一些显示出奇怪行为的 UITableViewController . 我在其中一个中定义了一个基本原型单元格,并在故事板中设置了标识符@ "standardCell" . 在相关的 UITableViewController 课程中,我是这样的:

- (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 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *cellIdentifier = @"standardCell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

   if (cell == nil) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
   }

   cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];

   return cell;
}

单元格会在显示表格视图时加载第一个单元格,但只要我滚动表格内容,所有设置的单元格 Headers 都显示为空,并且不再调用 cellForRowAtIndexPath: . didSelectRowAtIndexPath: 委托方法既未被调用 .

我已将此表视图的 delegatedataSource 都设置为表视图控制器 . 它的 .h 文件符合 UITableViewController <UITableViewDataSource, UITableViewDelegate> .

我发现了另一个表视图和相关视图控制器的类似问题,其中原型单元格是自定义单元格:当我滚动表格时,单元格显示错误的数据和奇怪的内容,就好像未按预期出列并重复使用的单元格 .

我能错过什么?

谢谢

1 回答

  • 1

    至少在这种方法中:

    改变这个:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
    static NSString *cellIdentifier = @"standardCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
     if (cell == nil) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];
    
    return cell;
    }
    

    对此:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {  
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"standardCell" forIndexPath:indexPath];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];
    
    return cell;
    }
    

相关问题