Лучший метод настройки типов ячеек UITableView для определенных ячеек - PullRequest
0 голосов
/ 16 января 2019

Я использую следующий код для установки типа требуемой ячейки, в зависимости от indexPath. Это такой грязный метод, и я уверен, что его можно каким-то образом убрать. Можно ли:

  1. Имеет ли оператор if проверку MULTIPLE int значений для indexPath? (Например, if indexPath.row == 0 or 1 or 2 {)
  2. Используйте оператор if, чтобы ТОЛЬКО установить идентификатор ячейки, а затем объявлять значение текстовых меток только после оператора if?

Или, если у кого-то есть другие идеи, как сделать его более практичным, я был бы очень признателен.

Вот код:

       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
    }

1 Ответ

0 голосов
/ 16 января 2019

Вы можете изменить if/else на:

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
}

Или используйте switch:

switch indexPath.row {
case 0, 5, 10, 14, 18:
    //timeCell
default:
    // default
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...