2010-11-03 87 views
0

我想显示自定义单元格,但我的代码只能一次显示一个自定义表格单元格。我做错了什么?自定义UITableViewCell只绘制一个单元格

我有一个UIViewController的笔尖与UIView里面的UITableView设置。在nib中还有一个UITableViewCell,它的类是CustomCell(UITableViewCell的一个子类)。 UITableView和Cell都是@synthesized IBOutlet @properties。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSString *CellIdentifier = @"CellIdentifier"; 
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; // CustomCell is the class for standardCell 
    if (cell == nil) 
    { 
     cell = standardCell; // standardCell is declared in the header and linked with IB 
    } 
    return cell; 
} 

回答

3

您可以使用下面的示例代码;


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSString *CellIdentifier = @"CellIdentifier"; 
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; // CustomCell is the class for standardCell 
    if (cell == nil) 
    { 
    NSArray *objectList = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil]; 
    for (id currentObject in objectList) { 
     if([currentObject isKindOfClass:[UITableViewCell class]]){ 
      cell = (CustomCell*)currentObject; 
      break; 
     } 
    } 
    } 
    return cell; 
} 
2

您应该创建一个新的电池每次dequeueReusableCellWithIdentifier回报nil

通常它应该看起来像

... 
if (cell == nil) 
{ 
    cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:nil options:nil] objectAtIndex:0] 
} 
... 

附:而不是objectAtIbndex:您可以通过返回的数组遍历和使用isKingOfClass:[MyCell class]找到小区

2

cell必须有它的内容设置为给定的索引路径,即使电池本身出列,如:

if (cell == nil) { 
    /* instantiate cell or load nib */ 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease]; 
} 

/* configure cell for a given index path parameter */ 
if (indexPath.row == 123) 
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
else 
    cell.accessoryType = nil; 
/* etc. */ 

return cell; 
0

如果cell == nil那么你需要实例化一个新UITableViewCell

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

    if (cell == nil) 
    { 
     // Instantiate a new cell here instead of using the "standard cell" 
     CustomCell *cell= [[[CustomCell alloc] init reuseIdentifier:CellIdentifier] autorelease]; 

     // Do other customization here 

    } 
    return cell; 
} 
相关问题