How to set the UITableView Section title programmatically (iPhone/iPad)?
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";
}
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
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
}