How to center the section headers of a UITableView
this should solve your issue. Tested in xcode 6 / ios8
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { [[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setTextAlignment:NSTextAlignmentCenter]; return [sectionTitles objectAtIndex:section];}
You must also implement tableView:heightForHeaderInSection to adjust your header height :
In the UITableViewDelegate Protocol Reference doc you find :
tableView:viewForHeaderInSection:
Discussion
The returned object, for example, canbe a UILabel or UIImageView object.The table view automatically adjuststhe height of the section header toaccommodate the returned view object.This method only works correctly whentableView:heightForHeaderInSection: isalso 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
Volker's answer in Swift:
If you target iOS6 and later you don't have to provide your own header view if you just want to center the header title.
Just implement
- tableView:willDisplayHeaderView:forSection:
and set the textAligment property of the label:
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let headerView = view as? UITableViewHeaderFooterView { headerView.textLabel?.textAlignment = .Center }}