Search code examples
iphoneuitableviewxcode4.5

Change backgroundColor of sectiontitle in UITableView


I have a UITableView with sections and the title for them I m setting in titleForHeaderInSection like this:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
  return [NSString stringwithFormat :@"Section %d",section];
}

Defaulty it comes with graycoloured background with textcolor white.How can I change it to some other colour.?

Gone through google and found to set in viewForHeaderinSection. But I did't use it to setheaders .So I dont want to write in it.

How can I write it in titleForHeaderInSection?


Solution

  • titleForHeaderInSection : This delegate of UITableView is used to set only text. You can see below it's return type it NSString.

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    {
        // fixed font style. use custom view (UILabel) if you want something different
    }
    

    In order to achieve the customized view for a section header your only option is viewForHeaderInSection delegate method. I can assure there's no way you can set the view for header using titleForHeaderInSection Also, viewForHeaderInSection acts exactly same as titleForHeaderInSection You can see implement it as below :

    -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        //Customized your view however you want.
    
        return myCustomizedView;
    }