UITableView change header title color
This is an old question, but I think the answer needs to be updated.
This method does not involve defining and creating your own custom view. In iOS 6 and up, you can easily change the background color and the text color by defining the
-(void)tableView:(UITableView *)tableView
willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)
delegate method.
For example:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// Background color
view.tintColor = [UIColor blackColor];
// Text Color
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor whiteColor]];
// Another way to set the background color
// Note: does not preserve gradient effect of original header
// header.contentView.backgroundColor = [UIColor blackColor];
}
Taken from my post here: https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/
Swift 5.0:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? UITableViewHeaderFooterView {
header.textLabel?.textColor = .white
}
}
Swift 4 version:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let headerView = view as? UITableViewHeaderFooterView else { return }
headerView.textLabel?.textColor = .red // any color
}
Implement the tableView:viewForHeaderInSection:
method in the tableViewController. That will allow you to supply your own view for the headers, which can include a UILabel with whatever formatting you want, e.g.
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UILabel *customLabel = [[UILabel alloc] init];
customLabel.text = [self tableView:tableView titleForHeaderInSection:section];
return customLabel;
}
Remember to set the label frame to be tall enough to space out the sections. You may wish to embed the label inside a larger UIView and return that instead to simplify positioning (e.g. if you want increase the left-padding on the label).
It took me a few minutes to "translate" this to Swift, but here's a working equivalent in Swift 1.2 (iOS 8). Be sure and implement UITableViewDelegate
in your class:
// MARK: - VIEW METHODS
override func viewDidLoad() {
tableView.delegate = self
}
// MARK: - TABLEVIEW DELEGATE METHODS
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.textLabel.textColor = UIColor.whiteColor()
}