Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating content size of UIView?

Tags:

ios

swift

I have a UITableView with a header on the top. In this header are other UIViews, UITextViews and UILables with dynamic heights

and I wondered, if there is a solution to calculate the content height of this header, so I can set its height in relation to its content. I know I could calculate it manually but sometimes such a function could be comfortable.

With Auto-Layout:

You can use this tutorial http://roadfiresoftware.com/2015/05/how-to-size-a-table-header-view-using-auto-layout-in-interface-builder/

override func viewDidLayoutSubviews() {
   super.viewDidLayoutSubviews()
   sizeHeaderToFit()
}

func sizeHeaderToFit() {
   let headerView = tableView.tableHeaderView!

   headerView.setNeedsLayout()
   headerView.layoutIfNeeded()

   let height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
   var frame = headerView.frame
   frame.size.height = height
   headerView.frame = frame

   tableView.tableHeaderView = headerView
}
like image 592
Julian Pomper Avatar asked Aug 17 '16 14:08

Julian Pomper


People also ask

What is intrinsic content size?

Intrinsic content size is information that a view has about how big it should be based on what it displays. For example, a label's intrinsic content size is based on how much text it is displaying. In your case, the image view's intrinsic content size is the size of the image that you selected.

What is content size Swift?

Most views have an intrinsic content size, which refers to the amount of space the view needs for its content to appear in an ideal state. For example, the intrinsic content size of a UILabel will be the size of the text it contains using whatever font you have configured it to use.

How does a view's intrinsic content size aid in auto layout?

In general, the intrinsic content size simplifies the layout, reducing the number of constraints you need. However, using the intrinsic content size often requires setting the view's content-hugging and compression-resistance (CHCR) priorities, which can add additional complications.


1 Answers

With Auto-Layout:

You can use this tutorial http://roadfiresoftware.com/2015/05/how-to-size-a-table-header-view-using-auto-layout-in-interface-builder/

override func viewDidLayoutSubviews() {
   super.viewDidLayoutSubviews()
   sizeHeaderToFit()
}

func sizeHeaderToFit() {
   let headerView = tableView.tableHeaderView!

   headerView.setNeedsLayout()
   headerView.layoutIfNeeded()

   let height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
   var frame = headerView.frame
   frame.size.height = height
   headerView.frame = frame

   tableView.tableHeaderView = headerView
}
like image 197
Julian Pomper Avatar answered Sep 21 '22 14:09

Julian Pomper