UITableViewStyleGrouped default header view?

uitableview

Solution

I got the bulk of the code from this blog which has only two posts, both from 2010. Then I went back to this site just for the font color, since it's more trouble to break apart.

Three minor problems, all with the label.

- Font is too narrow
- Text color is too dark
- Label origin is wrong

The default font is known, so that comes first.

label.font = [UIFont boldSystemFontOfSize:17.0];

Color is next, since that's easy. Used an image editor's Eyedropper tool for this.

label.textColor = [UIColor colorWithRed:0.298 green:0.337 blue:0.423 alpha:1];
// Is there a difference between alpha:1 and alpha:1.000?

Then the hard part. A close guess, and then some tweaking for a perfect match.

label.frame = CGRectMake(54, 4, headerView.frame.size.width-20, 22);

And now we have a custom implementation that perfectly matches the current Grouped header.

Finished code:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40)];
    tableView.sectionHeaderHeight = headerView.frame.size.height;

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(54, 4, labelSize.width, labelSize.height)];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setFont:[UIFont boldSystemFontOfSize:17.0]];
    [label setShadowColor:[UIColor whiteColor]];
    [label setShadowOffset:CGSizeMake(0, 1)];
    [label setText:[self tableView:tableView titleForHeaderInSection:section]];
    [label setTextColor:[UIColor colorWithRed:0.298 green:0.337 blue:0.423 alpha:1.000]];
    [headerView addSubview:label];

    return headerView;
}

Found this SO answer after finding the right font/color myself. Oh well.

Edit:

For a title label that allows an effectively unlimited amount of text:

// before label init
NSString *title = [self tableView:tableView titleForHeaderInSection:section];
NSUInteger maxWidth = headerView.frame.size.width-108;
CGSize labelSize = [title sizeWithFont:[UIFont systemFontOfSize:17.0]
                     constrainedToSize:CGSizeMake(maxWidth, CGFLOAT_MAX)];
if (labelSize.width < maxWidth) labelSize.width = maxWidth;

// after setFont:
[label setNumberOfLines:0];

Problem

I'm trying to implement a control for deleting entire sections, and it would look best in my app if the delete button was in the header, as opposed to an overlay like a UIPopoverView. In the process of writing this question, I found the answer. Easy enough, once there's a starting point.

Original source

Related problems