humbleCoder
humbleCoder

Reputation: 473

How to add space between header text and tableview

With iOS 11 I noticed how in Control Center they have a header view that has space between it's bottom part and the the tableview cell. How would you achieve this? heightForHeaderInSection only changes the height between the top of the header and whatever is above it, but not the space between the bottom part and the tableview.

enter image description here

UPDATE: Here is the code that worked for me for anyone else wondering.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, tableView.frame.size.width - 30, 50)];
    headerLabel.text = @"Text goes here";
    headerLabel.numberOfLines = 0;
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.textAlignment = NSTextAlignmentLeft;
    [headerLabel setFont:[UIFont fontWithName:@"Helvetica Neue" size:12.0]];
    // I could not figure out the exact text color :(
    [headerLabel setTextColor:[UIColor headingTextColor]];

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, headerLabel.frame.size.width, 200)];
    [headerView addSubview:headerLabel];

    return headerView;
}

Upvotes: 0

Views: 1877

Answers (1)

Milan Nosáľ
Milan Nosáľ

Reputation: 19765

I would try to do it by implementing tableView(_:viewForHeaderInSection:) and providing a custom view that would be used as a header. There you add a label as a subview and position it however you want.

tableView(_:viewForHeaderInSection:) works with UITableViewAutomaticDimension, but you can simply combine it with heightForHeaderInSection if you know the header height upfront.

Upvotes: 1

Related Questions