2010-11-03 91 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; 
} 
相關問題