Reputation: 747
I have a custom UIView which I want to be able to reuse throughout my application as a section header in tableviews. Here is the applicable code for that (this is basically all it is doing):
-(id) initWithTitle:(NSString *)title{
self = [super init];
if(self){
_title = title;
self.translatesAutoresizingMaskIntoConstraints = false;
[self addSubview:self.titleLabel];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-%@-[_titleLabel]-%@-|", HORIZONTAL_SPACE, HORIZONTAL_SPACE] options:0 metrics:nil views:NSDictionaryOfVariableBindings(self, _titleLabel)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-%@-[_titleLabel]-%@-|", VERTICAL_SPACE, VERTICAL_SPACE] options:0 metrics:nil views:NSDictionaryOfVariableBindings(self, _titleLabel)]];
[self updateConstraintsIfNeeded];
}
return self;
}
I am using it like this:
- (UIView*)tableView:(UITableView*)tableView
viewForHeaderInSection:(NSInteger)section
{
NSString *headerText = _headers[section];
if(headerText.length){
AWSmallTextSectionHeader *header = [[AWSmallTextSectionHeader alloc] initWithTitle:headerText];
return header;
}
return [UIView new];
}
The problem is that when the views draw to the screen they all start at the same origin...This is what is looks like at the top of the tableview:
It is really weird though because it is acting as if it is in the correct section, for example, if you start scrolling and one of the sections go offscreen, the view that corresponds to that section header will disappear.
I have a feeling it has to do with the way I am adding my constraints but I am not sure.
Thanks
Edit (this is also implemented)
- (CGFloat)tableView:(UITableView*)tableView
heightForHeaderInSection:(NSInteger)section
{
if (section == SECTION_INDEX_PHONE) {
return 60.f; //CGRectGetHeight(self.phoneSectionHeader.frame);
} else if (section == SECTION_INDEX_FEEDBACK) {
return 40.f; //CGRectGetHeight(self.feedbackSectionHeader.frame);
}
return 5.0;
}
Upvotes: 1
Views: 65
Reputation: 747
self.translatesAutoresizingMaskIntoConstraints = false;
was the problem.
Once I got rid of that it was working correctly.
Upvotes: 1
Reputation: 425
Should you at some point set the bounds for the header section view?
Also ensure you're adapting the heightForHeaderInSection:
This method only works correctly when tableView:heightForHeaderInSection: is also implemented.
Upvotes: 1