I'm trying to customize the headers for sections in a grouped table. The view I set for the first section in table looks fine, but subsequent section headers look like cropped at top and at bottom (in this screenshot it is only shown at top):
I've been trying different X and Y values for frame.size.origin
, but it remains looking the same. This is my code:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section == 1) {
UIView *wrapper = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 70)];
[wrapper setBackgroundColor:[UIColor clearColor]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, self.tableView.frame.size.width, 20)];
label.text = NSLocalizedString(@"Section 2 Header", @"");
[label setFont:[UIFont boldSystemFontOfSize:15]];
[label setBackgroundColor:[UIColor clearColor]];
[wrapper addSubview:label];
return wrapper;
}
else
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if (section == 1)
return 70;
else
return 0;
}
I do the same for all the section headers, and only the first one is correctly displayed, what could I'm doing wrong? Regarding this issue, is it possible to dynamically know the height of an UILabel
will take once its text and font size are known, or should you always set its frame size "at a guess"? The same for the height of view for the header that is set in heightForHeaderInSection:
method.
Thanks!
[label sizeToFit];
. This will ensure the label's frame properly fits the text. You might need to update the label's origin after that. – rmaddyif (section == 1)
or provideif (section == 2)
and etc.. Hope it help. Or you can call(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
and insert height for footer. – user2545330headerView.frame.size.height
inheightForHeaderInSection:
, or have you to supply a fixed value as I currently do? It looks likeheightForHeaderInSection:
method is called beforeviewForHeaderInSection:
method, but what if you don´t know at this point what the height of a label in a header will have? – AppsDev- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { return 30.0f; }
– user2545330