0

How can I get the height of a dynamic cell from the custom cell view.

I tried let height = contentView.layer.frame.height and let height = contentView.frame.height but all cells return 44 though the cells are different height.

On the viewController I have tableView.rowHeight = UITableView.automaticDimension.

Can anyone please help. Thanks

Omar d
  • 35
  • 3
  • Does this help https://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights? –  Aug 17 '20 at 17:58

1 Answers1

0

Swift 5 version. This should work.

func cellHeight(for indexPath: IndexPath) -> CGFloat {
    let cell = self.tableView.cellForRow(at: indexPath)
    return cell?.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height ?? 0
}

You can call this function after tableView.reloadData(). For example:

tableView.reloadData()
let indexPath = IndexPath(row: 0, section: 0) 
let height = cellHeight(for: indexPath)
print(height)

Important: You need to configure your cell correctly to be dynamic-heighted.

You don't have to call tableView.rowHeight = UITableView.automaticDimension because it's default value. More importantly, you need to set tableView.estimatedRowHeight properly.

Li Jin
  • 1,879
  • 2
  • 16
  • 23