Tom Testicool
Tom Testicool

Reputation: 563

Alternating between two different types of UITableViewCells

Scenario = I have a single tableView that will be loaded up by a single array of data (coming from internet, so I can't "hardcode" this). There will be two different tableView cells and I would like to alternate between the two types one right after the other. "CELL A" will have text on the right side and a picture on the left, and "CELL B" will have text on the left side and a picture on the right. Below I sort of illustrate the desired result (not meant to be "code" just to illustrate the alternation from cell to cell in the tableView).

tableView =
[0]indexPath.row = "CELL A"
[1]indexPath.row = "CELL B"
[2]indexPath.row = "CELL A"
[3]indexPath.row = "CELL B"
[4]indexPath.row = "CELL A"
[5]indexPath.row = "CELL B"

Problem = I am not sure how to dequeueForReuseIdentifier for two different types of cells.

Request = Can anyone help me with this code, or at least point me in the right direction, or is this even possible?

Thanks guys!

Upvotes: 1

Views: 249

Answers (2)

lucaslt89
lucaslt89

Reputation: 2451

In your storyboard, you should have a tableview with two prototype cells (one for cell A and another one for cell B). Set Identifiers for each cell (let say cellAIdentifier and cellBIdentifier).

You must also create subclasses of UITableViewCell for CellA and CellB. Then create the user interface in the prototype cell, and connect IBOutlets to the subclasses of UITableViewcell. Let say you use an IBOutlet called label, and another one called imageView.

After that, you can use rmaddy answer:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell;
    if (indexPath.row % 2 == 0) {
        cell = [tableview dequeueReusableCellWithIdentifier:@"cellAIdentifier"];
    } else {
        cell = [tableview dequeueReusableCellWithIdentifier:@"cellBIdentifier"];
    }
    label.text = @"your text, which should be taken from your model".
    imageView.image = [UIImage imageNamed:@"yourImageName"];
    return cell;
}

Good luck!

Upvotes: 1

rmaddy
rmaddy

Reputation: 318814

This is simple actually.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row % 2 == 0) {
        // setup and return table cell type A
    } else {
        // setup and return table cell type B
    }
}

Upvotes: 2

Related Questions