Friday, June 7, 2013

UITableView sectionHeaderHeight example in Objective C (iOS).


UITableView sectionHeaderHeight

The height of section headers in the receiving table view.

@property(nonatomic) CGFloat sectionHeaderHeight

Discussion of [UITableView sectionHeaderHeight]
This value is used only if delegate the doesn't implement the tableView:heightForHeaderInSection: method.

UITableView sectionHeaderHeight example.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0)
        return kFirstSectionHeaderHeight;
    return [self sectionHeaderHeight];
}

Example of [UITableView sectionHeaderHeight].
For all who want to shrink the distance to 0 you have to use:

tableView.sectionHeaderHeight = 0.0;
tableView.sectionFooterHeight = 0.0;
Because the serving of the UITableViewDelegate does only make an effect starting from floats greater than zero.

-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1.0;
}

-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
    return 1.0;
}

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
}

-(UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section
{
    return [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
}
(using iOS 4.1 with XCode 4.0.2)


UITableView sectionHeaderHeight example.
In the UITableViewController you can set tableView.sectionHeaderHeight to customise the height of all section headers. Using the UITableViewDelegate method:

tableView:viewForHeaderInSection:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UITableViewDelegate

You should return an instance of your custom UIView with the text label as the heading for the section.

You should add a shadow to the UILabel and adjust all colours to suit the default style. Since section headers are also slightly transparent, you can set your UIView alpha with

self.alpha = 0.9f;

End of UITableView sectionHeaderHeight example article.