How do you change the colour of a section title in a tableview?

AMAN77 picture AMAN77 · Sep 21, 2016 · Viewed 13.7k times · Source

Here is what I have at the moment.

enter image description here

How do I refer to this so that I can change the text colour to match my index list? The sectionForSectionIndexTitle worked well for adding in the correct section title but how exactly does one access the title element?

Or is it impossible and I need to redraw the view and add it with viewForHeaderInSection?

Answer

Anbu.Karthik picture Anbu.Karthik · Sep 21, 2016

you can use the one of UITableViewDelegate's method

swift3 and above

  func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? UITableViewHeaderFooterView {
        headerView.contentView.backgroundColor = .white
        headerView.backgroundView?.backgroundColor = .black
        headerView.textLabel?.textColor = .red
    }
}

objective C

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    if([view isKindOfClass:[UITableViewHeaderFooterView class]]){
        UITableViewHeaderFooterView * headerView = (UITableViewHeaderFooterView *) view;
        headerView.textLabel.textColor  = [UIColor RedColor];  
    }
}

for Reference I taken the model answer from here