indexPath.section在"cellForRowAtIndexPath:"中的奇怪行为



我对cellForRowAtIndexPath:方法中的indexPath.section有一个奇怪的问题。

我有一个包含4个部分的分组表视图,我正在尝试为第3部分应用自定义UITableViewCell,但它不起作用。

当我尝试if(indexPath.section==0){...}时,它有效(对于section==1section==2也是如此),但对于section==3它失败了。(?)

我不知道为什么,这毫无意义。。有人已经有这个(奇怪的)问题了吗?

当我尝试if(indexPath.row==0){...}时,它适用于所有4个部分。。所以

这是我的代码:

//ViewController.h
import "DirectionsTableViewCell.h"
DirectionsTableViewCell *directionsCell; // customized UITableViewCell
//ViewController.m
if (indexPath.section==3) {
        static NSString *CellIdentifier = @"directionsCell";
        DirectionsTableViewCell *cell = (DirectionsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil) {
            [[NSBundle mainBundle] loadNibNamed:@"DirectionsTableViewCell" owner:self options:nil];
            cell = directionsCell;
        }
        return cell;
    }
    else {
        static NSString *CellIdentifier = @"defaultCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        cell.textLabel.text = @"Test";
        return cell;
    }


问题解决了

我刚刚添加了if(indexPath.row),它运行良好。

最后你得到了这个:

if(indexPath.section==3) {
   if(indexPath.row) {
      static NSString *CellIdentifier = @"directionsCell";
      DirectionsTableViewCell *cell = (DirectionsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
      if(cell == nil) {
          [[NSBundle mainBundle] loadNibNamed:@"DirectionsTableViewCell" owner:self options:nil];
          cell = directionsCell;
      }
      return cell;
   }
}

好吧,您永远不会在if(cell == nil)中分配DirectionsTableViewCell。

在代码的这一部分:

DirectionsTableViewCell *cell = (DirectionsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil) {
            [[NSBundle mainBundle] loadNibNamed:@"DirectionsTableViewCell" owner:self options:nil];
            cell = directionsCell;
        }

您永远不会分配类型为DirectionsTableViewCell的单元格以便以后重用。我还注意到您有一个名为directionsCell的ivar,类型为DirectionsTableViewCell。除非您在其他地方进行分配和设置,否则cell = directionsCell最终会将一个nil对象分配给cell

试试这个代码,看看它是否有效:

static NSString *CellIdentifier = @"directionsCell";
directionsCell = (DirectionsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(directionsCell == nil) {
        directionsCell = [[DirectionsTableViewCell alloc] init]; //Or whatever your initializer is
    }
    return directionsCell;

最新更新