I have a UIView
subclass that contains a multi-line UILabel
. This view uses autolayout.
I would like to set this view as the tableHeaderView
of a UITableView
(not a section header). The height of this header will depend on the text of the label, which in turn depends on the width of the device. The sort of scenario autolayout should be great at.
I have found and attempted many many solutions to get this working, but to no avail. Some of the things I've tried:
- setting a
preferredMaxLayoutWidth
on each label duringlayoutSubviews
- defining an
intrinsicContentSize
- attempting to figure out the required size for the view and setting the
tableHeaderView
's frame manually. - adding a width constraint to the view when the header is set
- a bunch of other things
Some of the various failures I've encountered:
- label extends beyond the width of the view, doesn't wrap
- frame's height is 0
- app crashes with exception
Auto Layout still required after executing -layoutSubviews
The solution (or solutions, if necessary) should work for both iOS 7 and iOS 8. Note that all of this is being done programmatically. I've set up a small sample project in case you want to hack on it to see the issue. I've reset my efforts to the following start point:
SCAMessageView *header = [[SCAMessageView alloc] init];
header.titleLabel.text = @"Warning";
header.subtitleLabel.text = @"This is a message with enough text to span multiple lines. This text is set at runtime and might be short or long.";
self.tableView.tableHeaderView = header;
What am I missing?
Your constraints were just a little off. Take a look at this and let me know if you have any questions. For some reason I had difficulty getting the background of the view to stay red? So I created a filler view that fills the gap created by having a
titleLabel
andsubtitleLabel
height that is greater than the height of theimageView
This should do the trick for a headerView or a footerView for the UITableView using AutoLayout.