sizeToFit() returns wrong height - Need to find cell width in heightForRow

前端 未结 1 1654
有刺的猬
有刺的猬 2021-01-21 19:04

I am trying to make a UITableView with dynamic cell heights, based on the content. My app is an article viewer. I try to calculate the height of the cells with these functions.<

相关标签:
1条回答
  • 2021-01-21 19:42

    Automatic Dimension

    With much less code(*), you can ditch heightForRowAtIndexPath entirely, and use autolayout for everything.

    1. Do not overwrite heightForRowAtIndexPath (all that code goes away)
    2. Tell the table view to do the hard work (in viewDidLoad for example):
        self.tableView.estimatedRowHeight = 88
        self.tableView.rowHeight = UITableViewAutomaticDimension
    

    (*) 2 lines of code, to be precise. Convince yourself by comparing 2 lines solution against multiple methods override solution.


    Notes on margin

    • XIB & storyboard: you have the ability to control the constraints and their relationships to margin.
      Note that when using Relative to margin, the item order matters, as margins are generally insets. See https://stackoverflow.com/a/25420909/218152 for some details.

    • storyboard: you have access to the additional topLayoutGuide and bottomLayoutGuide properties from IB, which may be of value for your view controller, but are off-topic for your UITableViewCell.

    0 讨论(0)
提交回复
热议问题