Ambiguous layout with dynamic tableView height

后端 未结 2 800
旧时难觅i
旧时难觅i 2021-01-22 17:35

I have a viewController and I want to have two 1 tableView and 1 childViewController inside it.

  • tableView is non-scrollable with dynamic cell heights. (I\'m using
相关标签:
2条回答
  • 2021-01-22 18:15

    I suggest subclassing UITableView like this:

    class AutomaticHeightTableView: UITableView {
    
      override var intrinsicContentSize: CGSize {
        return contentSize
      }
    
      override func reloadData() {
        super.reloadData()
        invalidateIntrinsicContentSize()
      }
    }
    

    Then in Interface Builder set AutomaticHeightTableView as the class to your table view and the table will try to size itself to fit the content. It will follow any other constraints you placed so make sure the constraints allow it to grow freely.

    0 讨论(0)
  • 2021-01-22 18:34

    Table views and other scrollable views have no intrinsicContentSize. For example, your constraints would be fine if the participating views were say a UIImageView and a UILabel both of which can be sized by their content, but because your views are a UITableView and a UIView (neither can automatically size themselves, though you have enough constraints on the UIView to not be ambiguous) you'll need to do the sizing yourself.

    To get the behavior you desire, you will need to either subclass UITableView and override intrinsicContentSize or you'll need to set a height constraint. Either way, you'll need to calculate the correct height yourself. Content hugging and compression resistance allow auto layout to adjudicate between competing intrinsicContentSizes and is thus why they're not helping in this instance.

    For example:

    final class SizingTableView: UITableView {
        override var intrinsicContentSize: CGSize {
            return CGSize(width: bounds.width, height: <# Some appropriate height #>)
        }
    }
    

    Then in your storyboard or xib change the class of your table view to SizingTableView and you can set a design-time placeholder for the intrinsic content size of your table view in the size inspect to resolve any warning our errors.

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