iphoneuitableviewipadstoryboardiboutlet

How to set the UITableView Section title programmatically (iPhone/iPad)?


I've created a UITableView in Interface Builder using storyboards. The UITableView is setup with static cells and a number of different sections.

The issue I'm having is that I'm trying to setup my app in several different languages. To do this I need to be able to change the UITableView section titles somehow.

Please can someone help me out? Ideally I'd like to approach the issue using IBOutlets however I suspect this isn't even possible in this case. Any advice and suggestions would be really appreciated.


Solution

  • 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
    }