Multiple Custom Rows UITableView?

custom-cell, ios, iphone, uitableview

Solution

First you create some custom UITableViewCell classes (.h and .m), as many as you have xib files: So you could have CellType1 and CellType2 for example. CellType1.h would look something like

#import <UIKit/UIKit.h>
@interface CellType1 : UITableViewCell

@property(nonatomic,strong) IBOutlet UILabel *customLabel;

@end

Then you create the xib files, you can use default view type, but then, just remove the view that is automatically created, replace that by a UITableViewCell, and change the class to CellType1. Do the same for CellType2.

Then in your tableViewController, write cellForRow like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=nil;
//We use CellType1 xib for certain rows
if(indexPath.row==<whatever you want>){
     static NSString *CellIdentifier = @"CellType1";
     cell =(CellType1*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if(cell==nil){
        NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"CellType1" owner:self options:nil];
        cell = (CellType1 *)[nib objectAtIndex:0];
      }
      //Custom cell with whatever
      [cell.customLabel setText:@"myText"]
}
//We use CellType2 xib for other rows
else{
    static NSString *CellIdentifier = @"CellType2";
    cell =(CellType2*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if(cell==nil){
        NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"CellType2" owner:self options:nil];
        cell = (CellType2 *)[nib objectAtIndex:0];
      }
      //Custom cell with whatever
      [cell.customLabel setText:@"myText"]
}

return cell;
}

Problem

I've been searching a lot but didn't find anything useful related to multiple custom rows, I need to create a settings tableView for my app,in which I need to load the rows from xib files,like: ROW 1 =>> XIB 1. ROW 2 =>> XIB 2. ROW 3 =>> XIB 3. ROW 4 =>> XIB 4. My present code: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell=nil; //We use CellType1 xib for certain rows if(indexPath.row==0){ static NSString *CellIdentifier = @"ACell"; cell =(ACell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell==nil){ NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"ACell" owner:self options:nil]; cell = (ACell *)[nib objectAtIndex:0]; } //Custom cell with whatever //[cell.customLabelA setText:@"myText"] } //We use CellType2 xib for other rows else{ static NSString *CellIdentifier = @"BCell"; cell =(BCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell==nil){ NSArray *nib= [[NSBundle mainBundle] loadNibNamed:@"BCell" owner:self options:nil]; cell = (BCell *)[nib objectAtIndex:0]; } //Custom cell with whatever //[cell.customLabelB setText:@"myText"] } return cell; } ```

Original source