Liearth
Liearth

Reputation: 53

Is that possible to create multiple cells in one xib?

I found it can create different cells with different xibs, but I want to know is possible to create different cell in one xib? If possible, what should I can do this?

 here

Here is the code, I know it is wrong code, so can you guys help me to fix it?

- (void)viewDidLoad {
    [super viewDidLoad];

    [imageTableView registerNib:[UINib nibWithNibName:@"ImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"oneImageTableViewCell"];
    [imageTableView registerNib:[UINib nibWithNibName:@"ImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"twoImageTableViewCell"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier1 = @"oneImageTableViewCell";
    NSString *identifier2 = @"twoImageTableViewCell";
    if (indexPath.row % 2 == 0) {
        ImageTableViewCell *cell = [imageTableView dequeueReusableCellWithIdentifier:identifier1 forIndexPath:indexPath];
        return cell;
    } else {
        ImageTableViewCell *cell = [imageTableView dequeueReusableCellWithIdentifier:identifier2 forIndexPath:indexPath];
        return cell;
    }
}

Upvotes: 3

Views: 3287

Answers (1)

danh
danh

Reputation: 62686

My first idea would be to not do it. But if I had to do it, I guess I'd try building cells by using the old style dequeue, and, to build the initial pool of reusable cells, by manually extracting them from the nib.

So, don't do any cell nib or cell class registration, then in cellForRowAtIndexPath...

NSString *identifier;
NSInteger index;
if (indexPath.row % 2 == 0) {
    identifier = @"oneImageTableViewCell";
    index = 0;
} else {
    identifier = @"twoImageTableViewCell";
    index = 1;
}
UITableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"ImageTableViewCell" owner:self options:nil];
    cell = topLevelObjects[index];
}
return cell;

Upvotes: 3

Related Questions