How to add a caption title for each section in a table

I have four sections in my UITableView, how to add a title for each section? I am using the following code, but it does not work.

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { if (section == 0) return @"Tasks"; if (section == 1) return @"Appointments"; if (section == 2) return @"Activities"; if (section == 3) return @"Inactivities"; } 
+7
source share
3 answers

Are you sure you implemented tableView: heightForHeaderInSection :?

In your case, the names were actually set, but the default height of the headers was 0. Add this UITableViewDelegate method if you haven't already:

 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 40; //play around with this value } 

PS: Consider using the switch in such methods

+8
source

If the header height of your section is constant for each section, you do not need to implement the delegate method heightForHeaderInSection , and you can use below

 myTableView.sectionHeaderHeight = 40 ; 

Apple documentation

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html

+4
source

Change your if statements as follows

 if(section == 0) return @"ABC"; else if (section == 1) return @"XYZ"; else return @"PQR" 

Hope this helps. Please let me know if I can help.

Kick :)

-4
source

All Articles