Aaron
Aaron

Reputation: 353

Better method of setting UITableView cell types for specific cells

I am using the following code to set the type of cell required, depending on the indexPath. This is such a messy method and I'm sure it can be cleaned up in some way. Is it possible to:

  1. Have an if statement check MULTIPLE int values for the indexPath? (For example, if indexPath.row == 0 or 1 or 2 {)
  2. Use the if statement to ONLY set the cell identifier, and then only declare the value of the text labels after the if statement?

Or if anyone has any other ideas for ways to make it more practical, i'd really appreciate it.

Here's the code:

       if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "timeCell") as! FridayTableCell
        cell.dateLabel.text = tableViewData[indexPath.row].time
        return cell
    } else if indexPath.row == 5 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "timeCell") as! FridayTableCell
        cell.dateLabel.text = tableViewData[indexPath.row].time
        return cell
    } else if indexPath.row == 10 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "timeCell") as! FridayTableCell
        cell.dateLabel.text = tableViewData[indexPath.row].time
        return cell
    } else if indexPath.row == 14 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "timeCell") as! FridayTableCell
        cell.dateLabel.text = tableViewData[indexPath.row].time
        return cell
    } else if indexPath.row == 18 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "timeCell") as! FridayTableCell
        cell.dateLabel.text = tableViewData[indexPath.row].time
        return cell
    } else { //default
        let cell = tableView.dequeueReusableCell(withIdentifier: "default") as! FridayTableCell
        cell.dateLabel.text = tableViewData[indexPath.row].time
        cell.nameLabel.text = tableViewData[indexPath.row].name

       return cell
    }

Upvotes: 0

Views: 41

Answers (1)

rmaddy
rmaddy

Reputation: 318944

You can change the if/else to:

if [0, 5, 10, 14, 18].contains(indexPath.row) {
    //timeCell
    let cell = tableView.dequeueReusableCell(withIdentifier: "timeCell") as! FridayTableCell
    cell.dateLabel.text = tableViewData[indexPath.row].time
    return cell
} else {
    // default
    let cell = tableView.dequeueReusableCell(withIdentifier: "default") as! FridayTableCell
    cell.dateLabel.text = tableViewData[indexPath.row].time
    cell.nameLabel.text = tableViewData[indexPath.row].name

    return cell
}

Or use a switch:

switch indexPath.row {
case 0, 5, 10, 14, 18:
    //timeCell
default:
    // default
}

Upvotes: 3

Related Questions