Julian Pomper Julian Pomper - 2 months ago 14
Swift Question

Calculating content size of UIView?

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
}

Answer

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
}
Comments