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:
The constraints :
In the assets, my image has @2x and @3x sizes.
When I compile, in the simulator I obtain for iPhone 5:
For iPhone 6:
For iPhone 6+:
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...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With