Another way to do this would be to respond to the UITableViewDelegate
method willDisplayHeaderView
. The passed view is actually an instance of a UITableViewHeaderFooterView
.
The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respond to heightForHeaderInSection
to have any changes to your header's height accounted for in the layout of the table view. (That is, if you decide to change the header height in this willDisplayHeaderView
method.)
You could then respond to the titleForHeaderInSection
method to reuse this configured header with different section titles.
Objective-C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.textLabel.textColor = [UIColor redColor];
header.textLabel.font = [UIFont boldSystemFontOfSize:18];
CGRect headerFrame = header.frame;
header.textLabel.frame = headerFrame;
header.textLabel.textAlignment = NSTextAlignmentCenter;
}
Swift 1.2
(Note: if your view controller is a descendant of a UITableViewController
, this would need to be declared as override func
.)
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = UIColor.redColor()
header.textLabel.font = UIFont.boldSystemFontOfSize(18)
header.textLabel.frame = header.frame
header.textLabel.textAlignment = NSTextAlignment.Center
}
Swift 3.0
This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.textLabel?.textColor = UIColor.red
header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
header.textLabel?.frame = header.bounds
header.textLabel?.textAlignment = .center
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…