Reputation: 5247
I have custom tableView header, but the code where I specify header text color and separator line works only when the headers are dequeued, when I scroll them off the screen. Only then they return with white text color and visible separator. What is wrong with my code that the headers do not return in the correct state right on the first load?
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if (section == 0) {
return @"FIRST HEADER";
} else if (section == 1) {
return @"SECOND HEADER";
} else {
return @"THIRD HEADER";
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UITableViewHeaderFooterView *myHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
if (!myHeaderView) {
myHeaderView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"header"];
}
myHeaderView.textLabel.textColor = [UIColor whiteColor];
CGFloat leftMargin = 0.0;
CGFloat lineWidth = 1.0;
UIView *separatorLine = [[UIView alloc] initWithFrame:CGRectMake(leftMargin, myHeaderView.frame.size.height - lineWidth, myHeaderView.frame.size.width - leftMargin, lineWidth)];
separatorLine.backgroundColor = [UIColor whiteColor];
[myHeaderView addSubview:separatorLine];
return myHeaderView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 20.0;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
if ([view isMemberOfClass:[UITableViewHeaderFooterView class]]) {
((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = [UIColor clearColor];
}
}
Upvotes: 0
Views: 640
Reputation: 10313
The reason is that your header's frame is equal to CGRectZero
before dequeueing. It means, that header will be resized in future and you need to set appropriate autoresizing mask to separator. Then, separator will also be resized.
UIView *separatorLine = [[UIView alloc] initWithFrame:CGRectMake(leftMargin, 0, 0, lineWidth)];
separatorLine.backgroundColor = [UIColor redColor];
separatorLine.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
[header.contentView addSubview:separatorLine];
Upvotes: 1