Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adjust the height of the header of a tableview in swift?

I have a UITableViewController. This table view has an header view. I use main.storyboard with autolayout to set my controller.

In my main.storyboard, for w:Any h:Any, the preview of my view controller is set with the default size 600x600. Inside, my header view is set to 600x200.

In my header view, I have an imageView set to the Aspect Fill mode:

main.storyboard

The constraints :

constraints

In the assets, my image has @2x and @3x sizes.

When I compile, in the simulator I obtain for iPhone 5:

IPH5

For iPhone 6:

IPH6

For iPhone 6+:

IPH6+

  • For the iPhone 5, the image starts below the status bar. I don't understand why?
  • For the iPhone 6 and iPhone 6+, the image crops the first cell of my table view. And the top of the image isn't adjust with the top of the view.

I don't know how to adjust the height of the tableHeaderView to the height of my image, because this height depends on the device.

I have tried to set programmatically the frame of the header, in vain:

 var frame:CGRect!
 frame.size.width = self.bgHeaderImageView.image?.size.width
 frame.size.height = self.bgHeaderImageView.image?.size.height
 self.tableView.tableHeaderView?.frame = frame

I got 2 errors : "Value optional type CGFloat? not unwrapped"

And if I correct with

 var frame:CGRect!
 frame.size.width = self.bgHeaderImageView.image?.size.width!
 frame.size.height = self.bgHeaderImageView.image?.size.height!
 self.tableView.tableHeaderView?.frame = frame

I got 2 errors : "Operand of postfix ! should have optional type"

Is it to possible to adjust the size in the storyboard directly and not programmatically ?

I'm probably missing something here...

like image 334
cmii Avatar asked Mar 16 '23 16:03

cmii


1 Answers

The UITableView tableHeaderView has no option for aspect ratio and autolayout usage of the tableHeaderView is limited in InterfaceBuilder. There are many ways to achieve a dynamic height of the tableHeaderView. If you want to have a tableHeaderView height based on the ratio of a header image you can use:

let width = UIScreen.mainScreen().bounds.size.width
self.height = (width/640) * 209 //calculate new height
self.tableView.tableHeaderView?.frame.size = CGSize(width: self.tableView.tableHeaderView!.frame.size.width, height: self.height)
like image 92
Melvin Avatar answered Apr 26 '23 07:04

Melvin