设置UITableView分区头部的样式

20

我正在处理iOS 5,表格中有动态生成的单元格(2个部分,每个部分有3行),每个部分都有一个标题,也是使用titleForHeaderInSection调用动态生成的。

此外,我还将一张图片设置为表格的背景,导致默认颜色的部分标题难以阅读。我无法通过故事板界面或编程方式更改部分标题的颜色(或阴影颜色字体文本大小等)!请帮帮我!

5个回答

37

这也适用于 iOS5+。它适用于表视图中的所有部分头和脚,并满足我的需求。

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont fontWithName:@"MyFont" size:8]];
}


正是我所需要的,可以修改在Storyboard中定义的表格部分的外观,而无需实现tableView:viewForHeaderInSection:。谢谢! - Eric Baker
你不能在UILabel上使用外观代理。即使它能够工作,但它可能会在任何修订版本中被破坏。 - Cameron Lowell Palmer
在 Swift 2 中,您可以使用静态方法 appearanceWhenContainedInInstancesOfClasses(_:) 获取 UIAppearance 实例。例如,UILabel.appearanceWhenContainedInInstancesOfClasses([UITableViewHeaderFooterView.self]).textColor = UIColor.whiteColor() - Isaac Overacker

17

谢谢!这样就解决了! - Russell Winkler

13

实际上最简单的方法

如果你只需要进行一些简单的修改,例如改变字体或颜色:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *tableViewHeaderFooterView = (UITableViewHeaderFooterView *)view;
    tableViewHeaderFooterView.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:12.0f];
    tableViewHeaderFooterView.textLabel.textColor = [UIColor colorWithRed:0.27f green:0.27f blue:0.27f alpha:1.0f];
    tableViewHeaderFooterView.contentView.backgroundColor = [UIColor colorWithRed:0.87f green:0.87f blue:0.87f alpha:1.0f];
}

当我的部分文本跨越多行时,我遇到了问题:视图的高度不会相应地调整。有什么简单的方法可以解决这个问题吗? - Konrad
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/index.html#//apple_ref/occ/intfm/UITableViewDelegate/tableView:heightForHeaderInSection: - Cameron Lowell Palmer
这绝对是最简单的方法。赞! - Tim Kokesh

7
UITableViewHeaderFooterView类实现了可重用的视图,可以放置在表格段的顶部或底部。您可以使用标题和页脚来显示该部分的其他信息。
可用性:iOS(6.0及更高版本)
示例:
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setColor:[UIColor whiteColor]];

2
我更喜欢这个解决方案,因为你不必担心完全“重建”标题视图,如果你只想改变背景颜色或文本颜色。如果你使用setTextColor,它在iOS 7中确实有效。但是,如果你想自定义视图而不仅仅是交换一些颜色,那么使用一个全新的视图 - 就像被接受的答案建议的那样 - 可能是最好的方法。 - Habizzle

0

获取自定义节标题的最简单方法 - 使用单元格!

非常类似于用于的技术

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

您可以创建一个由您提供的单元格原型的实例。如果您的单元格包括标签的出口,您可以在返回之前设置它:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger) section
{
    SessionTableViewCell *cell;
    cell = [tableView dequeueReusableCellWithIdentifier:@"SessionSectionHeader"];
    if (cell == nil) {
        cell = [[SessionTableViewCell alloc]
               initWithStyle:UITableViewCellStyleDefault
             reuseIdentifier:@"SessionSectionHeader"];
    }
    cell.myLabel.text = myTitles[section];
    return cell;
}

请注意,@"SessionSectionHeader" 是我们单元格原型在故事板中的标识符。
希望对你有所帮助!

1
是的,除非您需要将部分标题显示为它们默认的方式(即使第一个部分单元格不在屏幕上方也固定在顶部)。 - Sea Coast of Tibet
这也破坏了可访问性,因为部分标题不再可识别。 - Robin Daugherty

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