How to set the UITableView Section title programmatically (iPhone/iPad)?
Once you have connected your UITableView delegate
and datasource
to your controller, you could do something like this:
ObjC
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *sectionName;
switch (section) {
case 0:
sectionName = NSLocalizedString(@"mySectionName", @"mySectionName");
break;
case 1:
sectionName = NSLocalizedString(@"myOtherSectionName", @"myOtherSectionName");
break;
// ...
default:
sectionName = @"";
break;
}
return sectionName;
}
Swift
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionName: String
switch section {
case 0:
sectionName = NSLocalizedString("mySectionName", comment: "mySectionName")
case 1:
sectionName = NSLocalizedString("myOtherSectionName", comment: "myOtherSectionName")
// ...
default:
sectionName = ""
}
return sectionName
}
If you are writing code in Swift it would look as an example like this
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
switch section
{
case 0:
return "Apple Devices"
case 1:
return "Samsung Devices"
default:
return "Other Devices"
}
}
Use the UITableViewDataSource method
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
titleForHeaderInSection is a delegate method of UITableView so to apply header text of section write as follows,
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return @"Hello World";
}
Note that -(NSString *)tableView:
titleForHeaderInSection:
is not called by UITableView if - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
is implemented in delegate of UITableView;