0

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.

arinjay
  • 83
  • 7
  • You should play around with the content hugging / compression resistance properties of the child views. – Andreas Oetjen Sep 25 '19 at 12:52
  • Possible duplicate of [iOS dynamical height of UITableViewCell and heightForRowAtIndexPath](https://stackoverflow.com/questions/31336472/ios-dynamical-height-of-uitableviewcell-and-heightforrowatindexpath) – Claudio Sep 25 '19 at 13:03
  • I have only one uiview in each of xib file,I have set content hugging priority to 246(both horizontal and vertical). Still not happening. – arinjay Sep 25 '19 at 13:04
  • you need to set a height to xib so tableView can calculate the height of row. – Enea Dume Sep 25 '19 at 13:13

2 Answers2

2

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.

0

Replace your UIView with UILabel and set number of lines to zero, Then it will automatically take the height based on the content of UILabel

Prakash Shaiva
  • 1,047
  • 8
  • 12