iosswiftuitableviewuikitrow-height

How to set the rowHeight of the first cell in a tableView


I would like to change the height of the first (top = index 0) cell in a table view, keeping the height of all other cells the same.

How can I do this?

Ideally I would like to be able to do this here:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   if shouldDisplaySuggestions && indexPath.row == 0 {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = "help"
        cell.textLabel?.font = UIFont(name: "SFCompactDisplay-Semibold", size: 17)

        return cell
    }

I set all other cells like:

tableView.rowHeight = 64.07

And this does not exist ->

tableView.cellForRow(at: IndexPath(row: 0, section: 0)).row...

Solution

  • You need to implement delegate method heightForRowAt

    func tableView(_ tableView: UITableView, 
         heightForRowAt indexPath: IndexPath) -> CGFloat {
          return indexPath.row == 0 ? 200 : 100
    }
    

    You could return dynamic for other cells also if you want to with

    return indexPath.row == 0 ? 200 : UITableView.automaticDimension
    

    Tip instead of

    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    

    Always use

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)!