Search code examples
iosswifttableviewxib

Tableview not getting Xib files height


I have created 3 custom .xib files for my tableview. But i am not able to figure out to specify the height of each cell.

I have implemented above line in viewdidLoad()

tableview.estimatedRowHeight = 120
tableview.rowHeight = UITableView.automaticDimension

I have just put a uiview in each of .xib file with 4 contraints (leading, trailing, top, bottom)

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

But it's not setting proper height to my cells.

its only when I hard code the value, only then it works.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }

How to handle this problem, as data will soon become dynamic and I can't be changing these hardcoded value.


Solution

  • UIView has not height value by default. As you trying it this will not set the height of cell.

    You can try by placing a UILabel or UIButton inside the UIView on which you have settled the 4 constraints (leading, trailing, top, bottom).

    NOTE: UILabel or UIButton also need 4 constraints (leading, trailing, top, bottom) if you want automatic height of UITableViewCell.