UITableView Mix of Static and Dynamic Cells?

前端 未结 6 1404
無奈伤痛
無奈伤痛 2020-11-28 07:57

I know you cannot mix Static and Dynamic cell types in a single UITableView but I couldn\'t think of a better way to describe my issue.

I have several p

6条回答
  •  伪装坚强ぢ
    2020-11-28 08:43

    1. Implement your tableView as normal using dynamic prototypes. For each custom cell, use 1 prototype. For an easy example, we'll use 2 cells, AddCell and RoomCell. AddCell is going in the first row, and RoomCell in the 2nd and any cell below.

    2. Remember to increase your count at numberofRowsInSection by the appropriate number of static cells (in this case 1). So if you're returning the count of an array to determine the number of rows, it'd be return array.count + 1 for this example since we have 1 static cell.

    3. I usually create a custom class for each cell as well. This typically makes it simpler to configure cells in the View Controller, and is a good way to separate code, but is optional. The example below is using a custom class for each cell. If not using a custom class, replace the if let statement with an if statement without an optional cast.

    note: configureCell below is a method in the custom class RoomCell that dynamically configures the cell

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            if let cell =  tableView.dequeueReusableCell(withIdentifier: "AddCell", for: indexPath) as? AddCell {
                return cell
            }
        } else {
            if let cell = tableView.dequeueReusableCell(withIdentifier: "RoomCell", for: indexPath) as? RoomCell {
                cell.configureCell(user: user, room: room)
                return cell
            }
        }
        return UITableViewCell() //returns empty cell if something fails
    }
    

提交回复
热议问题