Ambiguous layout with dynamic tableView height

為{幸葍}努か 提交于 2019-12-02 00:48:59

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!