如何以编程方式设置UITableView的章节标题(iPhone/iPad)?

116

我使用storyboards在Interface Builder中创建了一个带有静态单元格和多个不同部分的UITableView

我的问题是,我正在尝试以几种不同的语言设置我的应用程序。 为此,我需要能够以某种方式更改UITableView的部分标题。

请有人能帮我吗? 理想情况下,我想使用IBOutlets来解决这个问题,但我怀疑在这种情况下甚至都不可能。 任何建议和建议都将不胜感激。


未来的读者请注意:'有人可以帮我吗?'不是一个实际的问题。请确保提出明确、聚焦的问题。 - starball
9个回答

291

一旦您将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;
}

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
}

你确定如果使用静态单元格设置故事板,它会被调用吗?看起来好像没有被调用。 - drewish
7
似乎你需要实现 numberOfSectionsInTableView:tableView: 方法才能让它被调用。 - drewish
对于静态单元格,(大多数)其他数据源方法未实现。 - wcochran
2
在IB中为静态单元格实现了numberOfSectionsInTableView:tableView: - wcochran
但是你如何动态更改标题?你如何调用这个方法? - Blip
显示剩余2条评论

18

如果您正在使用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"
    }
}

10

使用 UITableViewDataSource 方法。

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

6

titleForHeaderInSection 是 UITableView 的一个委托方法,用于设置 section 的标题文本。使用如下代码编写:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"Hello World";
}

3
请注意,如果UITableView的代理实现了- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section方法,则-(NSString *)tableView:titleForHeaderInSection:方法不会被UITableView调用;

2

其他答案都没有问题,但这个答案提供了一种非编程解决方案,适用于静态表格的情况。好处是可以使用故事板来组织本地化内容。可以继续通过Xcode导出XLIFF文件进行本地化。Xcode 9还有几个新工具使本地化更加容易

(原始文本)

我有一个类似的需求。在我的Main.storyboard(Base)中有一个带有静态单元格的静态表格。要使用.string文件对部分标题进行本地化,例如Main.strings(German),只需在故事板中选择该部分并注意对象ID即可。

Object ID

之后,进入您的字符串文件,以我的情况为例,是Main.strings(German),并插入翻译,例如:

"MLo-jM-tSN.headerTitle" = "Localized section title";

其他资源:


2
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   return 45.0f; 
//set height according to row or section , whatever you want to do!
}

设置部分标签文本。

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionHeaderView;

        sectionHeaderView = [[UIView alloc] initWithFrame:
                             CGRectMake(0, 0, tableView.frame.size.width, 120.0)];


    sectionHeaderView.backgroundColor = kColor(61, 201, 247);

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:
                            CGRectMake(sectionHeaderView.frame.origin.x,sectionHeaderView.frame.origin.y - 44, sectionHeaderView.frame.size.width, sectionHeaderView.frame.size.height)];

    headerLabel.backgroundColor = [UIColor clearColor];
    [headerLabel setTextColor:kColor(255, 255, 255)];
    headerLabel.textAlignment = NSTextAlignmentCenter;
    [headerLabel setFont:kFont(20)];
    [sectionHeaderView addSubview:headerLabel];

    switch (section) {
        case 0:
            headerLabel.text = @"Section 1";
            return sectionHeaderView;
            break;
        case 1:
            headerLabel.text = @"Section 2";
            return sectionHeaderView;
            break;
        case 2:
            headerLabel.text = @"Section 3";
            return sectionHeaderView;
            break;
        default:
            break;
    }

    return sectionHeaderView;
}

2

我不知道以前的UITableView协议版本,但在iOS 9中,func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?UITableViewDataSource协议的一部分。

   class ViewController: UIViewController {

      @IBOutlet weak var tableView: UITableView!

      override func viewDidLoad() {
         super.viewDidLoad()
         tableView.dataSource = self
      }
   }

   extension ViewController: UITableViewDataSource {
      func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
         return "Section name"
      }
   }

在填充表格数据时,您不需要声明delegate


在Swift 5.3中似乎不需要使用“extension”。Xcode构建消息:“'SettingsViewController'从超类继承对协议'TableViewDataSource'的一致性”。 - l --marc l

0

在这里输入图片描述[![在这里输入图片描述][2]][2]带有自定义设计的分区设计的tableView

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let width = width(text: myArr[section].date, height: 30)
    let headerLabel:UILabel = UILabel.init(frame: CGRect(x: self.view.frame.width / 2 - ((width + 30) / 2), y: 0, width: width + 30, height: 30))
    headerLabel.text = myArr[section].date
    headerLabel.textColor = UIColor.white
    headerLabel.backgroundColor = UIColor.AppRed
    headerLabel.textAlignment = .center
    headerLabel.layer.masksToBounds = true
    headerLabel.layer.cornerRadius = 10

    let headerView:UIView = UIView.init(frame: CGRect(x: 0 , y: 0, width: self.view.frame.size.width, height: 40))
    headerView.backgroundColor = UIColor.clear
    headerView.addSubview(headerLabel)
    headerView.layer.cornerRadius = 10
    return headerView
    
}
func width(text: String, height: CGFloat) -> CGFloat {
    let attributes: [NSAttributedString.Key: Any] = [
        .font: UIFont.systemFont(ofSize: 17)
    ]
    let attributedText = NSAttributedString(string: text, attributes: attributes)
    let constraintBox = CGSize(width: .greatestFiniteMagnitude, height: height)
    let textWidth = attributedText.boundingRect(with: constraintBox, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).width.rounded(.up)
    
    return textWidth
}

定制的桌子部分设计

https://istack.dev59.com/U9VIv.webp


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接