如何以编程方式设置UITableView部分标题(iPhone/iPad)?

The*_*imp 105 iphone uitableview iboutlet ipad uistoryboard

UITableView在Interface Builder中创建了一个storyboards.的UITableView是设置有static cells与多个不同的部分.

我遇到的问题是我正在尝试用几种不同的语言设置我的应用程序.要做到这一点,我需要能够以UITableView某种方式更改部分标题.

请有人帮帮我吗?理想情况下,我想用这个问题来解决这个问题,IBOutlets但我怀疑在这种情况下甚至不可能.任何建议和意见将非常感谢.

提前致谢.

All*_*ian 277

一旦你连接你的UITableView delegatedatasource你的控制器,你可以这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

迅速

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
}
Run Code Online (Sandbox Code Playgroud)

  • 啊,似乎你必须实现`numberOfSectionsInTableView:tableView:`来调用它. (7认同)
  • @drewish`numberOfSectionsInTableView:tableView:`在IB中为静态单元格实现. (2认同)

小智 15

如果你在Swift中编写代码,它就像这样的例子

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
    switch section
    {
        case 0:
            return "Apple Devices"
        case 1:
            return "Samsung Devices"
        default:
            return "Other Devices"
    }
}
Run Code Online (Sandbox Code Playgroud)


ger*_*iam 10

使用UITableViewDataSource方法

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
Run Code Online (Sandbox Code Playgroud)


iAn*_*kit 5

titleForHeaderInSectionUITableView委托方法,因此要应用section write的头文本,如下所示,

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
              return @"Hello World";
}
Run Code Online (Sandbox Code Playgroud)