Dynamic Height Issue for UITableView Cells (Swift)

前端 未结 25 2641
温柔的废话
温柔的废话 2020-11-28 04:39

Dynamic text of variable length are being injected into tableview cell labels. In order for the tableview cells\' heights to be dynamically sized, I have implemented in

25条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 05:01

    This strange bug was solved through Interface Builder parameters as the other answers did not resolve the issue.

    All I did was make the default label size larger than the content potentially could be and have it reflected in the estimatedRowHeight height too. Previously, I set the default row height in Interface Builder to 88px and reflected it like so in my controller viewDidLoad():

    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 88.0
    

    But that didn't work. So I realized that content wouldn't ever become larger than maybe 100px, so I set the default cell height to 108px (larger than the potential content) and reflected it like so in the controller viewDidLoad():

    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 108.0
    

    This actually allowed the code to shrink down the initial labels to the correct size. In other words, it never expanded out to a larger size, but could always shrink down... Also, no additional self.tableView.reloadData() was needed in viewWillAppear().

    I know this does not cover highly variable content sizes, but this worked in my situation where the content had a maximum possible character count.

    Not sure if this is a bug in Swift or Interface Builder but it works like a charm. Give it a try!

提交回复
热议问题