ios - UITableView: Set table header view height based on screen size -
i have table view table header view created through interface builder inside same xib. want set height of header based on screen size, example 50% of screen height.
here static height on iphone 4s:
and here is on iphone 6:
note content of header static.
i cannot set constraints header using auto layout. tried set height constraint based on height of table view not seem possible in interface builder. control-dragging not work. cannot drag line header table view or header itself.
how can set header's height based on screen size?
unfortunately, table header views cannot sized using auto layout. can use auto layout elements inside header have specify header's size explicitly setting frame. if header's height static , known @ compile time can use ib. however, if height dynamic or depends on device (as in case), have set in code.
a quite flexible solution create custom subclass of uitableview
, adapt header's frame in layoutsubviews
method. way header's size gets automatically adjusted when table view resized. have careful, however, re-apply header's frame when change needed avoid infinite loop.
here's in objective-c:
@interface mytableview : uitableview @end @implementation mytableview : uitableview - (void)layoutsubviews { [super layoutsubviews]; if (self.tableheaderview) { uiview *header = self.tableheaderview; cgrect rect = cgrectmake(0, 0, self.bounds.size.width, self.bounds.size.height / 2); // adjust frame if needed avoid infinite loop if (!cgrectequaltorect(self.tableheaderview.frame, rect)) { header.frame = rect; // apply new header size , trigger // call of layoutsubviews self.tableheaderview = header; } } } @end
the swift version looks this:
class mytableview: uitableview { override func layoutsubviews() { super.layoutsubviews() if let header = tableheaderview { let rect = cgrectmake(0, 0, bounds.size.width, bounds.size.height / 2) // adjust frame if needed avoid infinite loop if !cgrectequaltorect(header.frame, rect) { header.frame = rect // apply new header size , trigger // call of layoutsubviews tableheaderview = header } } } }
note above snippets use bounds of table view rather screen size calculate header size.
update: note additional call layoutifneeded
needed after setting tableheaderview
property. ran issue section headers drawn above header view without calling layoutifneeded
.
Comments
Post a Comment