Mark Mark - 3 months ago 6
iOS Question

How to center the section headers of a UITableView

I want to center the header on the tableview, however I have 2 problems. First I don't have the correct height and second the UILabel doesn't look like the default header - font/font size/color etc... Is there a better way to center it, and/or is there a way to make it look like the default header.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger) section
//section text as a label
UILabel *lbl = [[UILabel alloc] init];
lbl.textAlignment = UITextAlignmentCenter;

lbl.text = @"Header";
[lbl setBackgroundColor:[UIColor clearColor]];

return lbl;


You must also implement tableView:heightForHeaderInSection to adjust your header height :

In the UITableViewDelegate Protocol Reference doc you find :



The returned object, for example, can be a UILabel or UIImageView object. The table view automatically adjusts the height of the section header to accommodate the returned view object. This method only works correctly when tableView:heightForHeaderInSection: is also implemented.

For centering the Header label you must specify the label frame before setting its aligment to center. For getting the standart font, use SystemFontOfSize:

Also beware you are creating a memory leak you are supposed to return an autoreleased view

Try something like this :

UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)] autorelease];
lbl.textAlignment = UITextAlignmentCenter;
lbl.font = [UIFont systemFontOfSize:12];

Hope this helps, Vincent