Gugulethu
Gugulethu

Reputation: 1436

Putting multiple type TableViewCells in the same Table View

I have a table view that is currently displaying a type of tableViewCell creating in a XIB File and I want to display a different type of XIB file in the table View at random Places. e.g. Like having Ad display Cells in a tableview at Random Post positions.

How can I do this. I currently have the following code for displaying one Cell:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cardioCell:CardioItemsTableViewCell! = tableView.dequeueReusableCellWithIdentifier("CardioItemsTableViewCell") as? CardioItemsTableViewCell
cardioCell.cellNameLabel.text = "Test String"

return cardioCell!

}

I have this image of the apple news App with one cell without an image. In my instance though, the cell is completely different and has a different layout to the other cells.

Any ideas would be much appreciated.

enter image description here

Upvotes: 0

Views: 863

Answers (1)

Natasha
Natasha

Reputation: 6893

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if indexPath.row % 2 == 0
        let cardioCell:CardioItemsTableViewCell! = tableView.dequeueReusableCellWithIdentifier("CardioItemsTableViewCell") as? CardioItemsTableViewCell
        cardioCell.cellNameLabel.text = "Cells with even number of row"
        return cardioCell!

    else if indexPath.row % 2 != 0
        let otherTypeCell:OtherTypeTableViewCell! = tableView.dequeueReusableCellWithIdentifier("OtherTypeItemsTableViewCell") as? OtherTypeTableViewCell
        otherTypeCell.cellNameLabel.text = "Cells with odd number of row"
        return otherTypeCell!
}

You can not load cells randomly. You need to have a certain logic based on which you can load different types of tableViewCell.

Upvotes: 2

Related Questions