0

很好奇如何从 tableView:cellForRowAtIndexPath: 中处理自定义表格单元格。

我在 viewDidLoad 中实例化了一个自定义表格单元格。我的问题是,当没有可重复使用的单元格时,如何处理 cellForRowAtIndexPath 中的情况?例如,返回搜索结果时。如果需要,如何创建新的自定义单元格?我在下面包括了相关的方法。

谢谢

 -(void)viewDidLoad
 {
   [super viewDidLoad];

   //Load custom table cell
     UINib *customCellNib = [UINib nibWithNibName:@"CustomItem" bundle:nil];

   //Register this nib, which contains the cell
    [[self tableView] registerNib:customCellNib forCellReuseIdentifier:@"CustomItemCell"];


   //.... More stuff here

  }


  - (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {

     CustomItemCell *cell =
    [tableView dequeueReusableCellWithIdentifier:@"CustomItemCell"];

     // If there is no reusable cell of this type, create a new one
     if (!cell) {


       //Is this right?
       cell = [[CustomItemCell alloc] init];

     }




          //Set up cell with data here...



    return cell;
 }
4

1 回答 1

0

I ended up solving this by accessing the main bundle, looking for the custom table cell nib file. When we find our custom table cell class, we assign iVar "cell" to that object.

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

   static NSString *cellID = @"CustomItemCell";
   CustomItemCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

   // If there is no reusable cell of this type, create a new one

   if(cell == nil){


    NSArray *nibObjects = [[NSBundle mainBundle]loadNibNamed:@"CustomCell" owner:nil options:nil];
    for (id currentObject in nibObjects) {
        if([currentObject isKindOfClass:[CustomItemCell class]])
        {
            cell = (CustomItemCell *)currentObject;

        }


    }

  } 
   //Assign data to cell here   
}
于 2012-06-28T19:51:17.200 回答