TableView与多个原型单元格

我有一个关于3种不同types原型单元的表格视图的简单问题。 前两次出现一次,而第三次出现四次。 现在我感到困惑的是如何在我的cellforRowatindexpath中指定哪个单元格原型用于哪一行。 所以,我想像行0,使用原型1,行1,使用原型2,行3,4,5和6使用原型3.什么是最好的方法来做到这一点? 我给每个原型标识符,然后使用dequeueReusableCellWithIdentifier:CellIdentifier? 你能提供一些示例代码吗?

编辑:

还是行不通。 这是我目前的代码。 (我只有一个开关状态的例子,因为我只是想testing一下,看是否在第一行中生成单元格,但是当前表格视图是空白的)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { switch(indexPath.row) { case 0: {static NSString *CellIdentifier = @"ACell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ACell"]; if(cell==nil) { cell=[[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"ACell"]; } return cell; break; } } } 

Acell是我创build的单元格原型的标识符。 一世

如果您使用三个原型,则使用三个标识符。 因为只有一个标识符会导致问题。 你会得到错误的结果。 所以这样的代码。

 if(indexPath.row==0){ // Create first cell } if(indexPath.row==1){ // Create second cell } else{ // Create all others } 

您也可以在这里使用开关盒以获得最佳性能。

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if (cell.tag == 0) { return array1.count; } else(cell.tag == 1) { return array2.count; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier; NSString *membershipType = [membershipTypeArray objectAtIndex:indexPath.row]; if ([membershipType isEqualToString:@"silver"]||[membershipType isEqualToString:@"gold"]) { cellIdentifier = @"cell"; } else if ([membershipType isEqualToString:@"platinum"]) { cellIdentifier = @"premiumCustomCell"; cell.customCellImageView.image = [cellImageArray objectAtIndex:indexPath.row]; } cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } cell.selectionStyle = UITableViewCellSelectionStyleNone; cell.headingLabel.text = [titleArray objectAtIndex:indexPath.row]; } 

在这里我写了如下代码:

 #pragma mark == Tableview Datasource - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 2; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSInteger nRows = 0; switch (section) { case 0: nRows = shipData.count; break; case 1: nRows = dataArray1.count; break; default: break; } return nRows; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ NSString *cellIdentifier = @"cellIdentifier1"; NSString *cellIdentifier1 = @"cellIdentifier2"; SingleShippingDetailsCell *cell; switch (indexPath.section) { case 0: cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; //Load data in this prototype cell break; case 1: cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1]; //Load data in this prototype cell break; default: break; } return cell; }