Home > DeveloperSection > Forums > How to set different section titles in UITableView in Objective-C?
naomi burke
naomi burke

Total Post:28

Posted on    February-28-2016 11:32 PM

 iPhone iPhone  Ios  Objective C 

 1 Reply(s)
 624  View(s)
Rate this:

I have created an Contact application and displaying it into the UITableVIew. I want to display the contact names in different sections with different section titles.
currently I am using numberOfSectionsInTableView: the table view delegate method for managing sections, like this:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    return 1;

but as you can see that currently I am returning 1 which is creating only one section. My main problem is to display different section titles, So can you tell me that how can we set the section headers without repeating titles?

Tarun Kumar

Total Post:214

Posted on    February-29-2016 11:54 PM

UITableView provides a delegate method titleForHeaderInSection: for setting the section titles.
Here is an example: we have an array of sectionTitles:
NSArray *sectionTitles = [[NSArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",nil];
now return the total no of sections in the numberOfSectionsInTableView: method, like this:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)searchBar
  return [sectionTitles count];

and return the section titles in titleForHeaderInSection: method, like this:

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  return [sectionTitles objectAtIndex:section];

above method is responsible for putting the titles of sections using the sectionTitles array.

Don't want to miss updates? Please click the below button!

Follow MindStick