Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 613
AMAN77 Avatar asked Sep 21 '16 10:09

AMAN77


People also ask

How do I change the background color of a table in Swift?

Basic Swift Code for iOS Apps For changing the background color of the table view cell, you should change the contentView. backgroundColor property of the cell. Now run the project to see the effect.

What is UITableView?

UITableView manages the basic appearance of the table, but your app provides the cells ( UITableViewCell objects) that display the actual content. The standard cell configurations display a simple combination of text and images, but you can define custom cells that display any content you want.


2 Answers

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

like image 140
Anbu.Karthik Avatar answered Oct 20 '22 10:10

Anbu.Karthik


One liner solution (using optional chaining):

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    (view as? UITableViewHeaderFooterView)?.textLabel?.textColor = UIColor.red
}
like image 34
Federico Zanetello Avatar answered Oct 20 '22 11:10

Federico Zanetello