ios 更改 UITableView 部分标题的字体大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19802336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:46:38  来源:igfitidea点击:

Changing Font Size For UITableView Section Headers

iosobjective-cswiftuitableviewuitableviewsectionheader

提问by JRD8

Can someone please instruct me on the easiest way to change the font size for the text in a UITableView section header?

有人可以指导我更改 UITableView 部分标题中文本字体大小的最简单方法吗?

I have the section titles implemented using the following method:

我使用以下方法实现了部分标题:

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

Then, I understand how to successfully change the section header height using this method:

然后,我了解如何使用此方法成功更改节标题高度:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

I have the UITableView cells populated using this method:

我使用此方法填充了 UITableView 单元格:

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

However, I'm stuck as to how to actually increase the font size - or for that matter the font style - of the section header text?

但是,我不知道如何实际增加节标题文本的字体大小 - 或者就此而言字体样式?

Can someone please assist? Thanks.

有人可以帮忙吗?谢谢。

采纳答案by mosca1337

Unfortunately, you may have to override this:

不幸的是,您可能必须覆盖这一点:

In Objective-C:

在 Objective-C 中:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

In Swift:

在斯威夫特:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

Try something like this:

尝试这样的事情:

In Objective-C:

在 Objective-C 中:

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

    UILabel *myLabel = [[UILabel alloc] init];
    myLabel.frame = CGRectMake(20, 8, 320, 20);
    myLabel.font = [UIFont boldSystemFontOfSize:18];
    myLabel.text = [self tableView:tableView titleForHeaderInSection:section];

    UIView *headerView = [[UIView alloc] init];
    [headerView addSubview:myLabel];

    return headerView;
}

In Swift:

在斯威夫特:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let myLabel = UILabel()
    myLabel.frame = CGRect(x: 20, y: 8, width: 320, height: 20)
    myLabel.font = UIFont.boldSystemFont(ofSize: 18)
    myLabel.text = self.tableView(tableView, titleForHeaderInSection: section)

    let headerView = UIView()
    headerView.addSubview(myLabel)

    return headerView
}

回答by Mark Semsel

Another way to do this would be to respond to the UITableViewDelegatemethod willDisplayHeaderView. The passed view is actually an instance of a UITableViewHeaderFooterView.

另一种方法是响应UITableViewDelegate方法willDisplayHeaderView。传递的视图实际上是 a 的一个实例UITableViewHeaderFooterView

The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respond to heightForHeaderInSectionto have any changes to your header's height accounted for in the layout of the table view. (That is, if you decide to change the header height in this willDisplayHeaderViewmethod.)

下面的示例更改字体,并在单元格内垂直和水平居中标题文本。请注意,您还应该响应heightForHeaderInSection表格视图布局中对标题高度的任何更改。(也就是说,如果您决定在此willDisplayHeaderView方法中更改标题高度。)

You could then respond to the titleForHeaderInSectionmethod to reuse this configured header with different section titles.

然后,您可以响应该titleForHeaderInSection方法以使用不同的部分标题重用此配置的标题。

Objective-C

目标-C

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;

    header.textLabel.textColor = [UIColor redColor];
    header.textLabel.font = [UIFont boldSystemFontOfSize:18];
    CGRect headerFrame = header.frame;
    header.textLabel.frame = headerFrame;
    header.textLabel.textAlignment = NSTextAlignmentCenter;
}

Swift 1.2

斯威夫特 1.2

(Note: if your view controller is a descendant of a UITableViewController, this would need to be declared as override func.)

(注意:如果您的视图控制器是 a 的后代,则UITableViewController需要将其声明为override func。)

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) 
{
    let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView

    header.textLabel.textColor = UIColor.redColor()
    header.textLabel.font = UIFont.boldSystemFontOfSize(18)
    header.textLabel.frame = header.frame
    header.textLabel.textAlignment = NSTextAlignment.Center
}

Swift 3.0

斯威夫特 3.0

This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView:

如果您的标题视图不是 UITableViewHeaderFooterView,此代码还可以确保应用程序不会崩溃:

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let header = view as? UITableViewHeaderFooterView else { return }
    header.textLabel?.textColor = UIColor.red
    header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
    header.textLabel?.frame = header.frame
    header.textLabel?.textAlignment = .center
}

回答by Leo Natan

While mosca1337's answer is a correct solution, be careful with that method. For a header with text longer than one line, you will have to perform the calculations of the height of the header in tableView:heightForHeaderInSection:which can be cumbersome.

虽然 mosca1337 的答案是正确的解决方案,但要小心使用该方法。对于文本长度超过一行的标题,您必须执行标题高度的计算,tableView:heightForHeaderInSection:这可能很麻烦。

A much preferred method is to use the appearance API:

一个更受欢迎的方法是使用外观 API:

[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:28]];

This will change the font, while still leaving the table to manage the heights itself.

这将改变字体,同时仍然离开表格来管理高度本身。

For optimal results, subclass the table view, and add it to the containment chain (in appearanceWhenContainedIn:) to make sure the font is only changed for the specific table views.

为获得最佳结果,将表格视图子类化,并将其添加到包含链(在 中appearanceWhenContainedIn:)以确保仅更改特定表格视图的字体。

回答by Maria

For iOS 7 I use this,

对于 iOS 7 我使用这个,


-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;

    header.textLabel.font = [UIFont boldSystemFontOfSize:10.0f];
    header.textLabel.textColor = [UIColor orangeColor];
}

Here is Swift 3.0version with header resizing

这是带有标题大小调整的Swift 3.0版本

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let header = view as? UITableViewHeaderFooterView {
        header.textLabel!.font = UIFont.systemFont(ofSize: 24.0)
        header.textLabel!.textColor = UIColor.orange          
    }
}

回答by jeff-ziligy

Swift 3:

斯威夫特 3:

Simplest way to adjust onlysize:

调整大小的最简单方法:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    let header = view as! UITableViewHeaderFooterView

    if let textlabel = header.textLabel {
        textlabel.font = textlabel.font.withSize(15)
    }
}

回答by Elliott Davies

Swift 2.0:

斯威夫特 2.0

  1. Replace default section header with fully customisable UILabel.
  1. 用完全可定制的 UILabel 替换默认部分标题。

Implement viewForHeaderInSection, like so:

实现 viewForHeaderInSection,如下所示:

  override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let sectionTitle: String = self.tableView(tableView, titleForHeaderInSection: section)!
    if sectionTitle == "" {
      return nil
    }

    let title: UILabel = UILabel()

    title.text = sectionTitle
    title.textColor = UIColor(red: 0.0, green: 0.54, blue: 0.0, alpha: 0.8)
    title.backgroundColor = UIColor.clearColor()
    title.font = UIFont.boldSystemFontOfSize(15)

    return title
  }
  1. Alter the default header (retains default).
  1. 更改默认标题(保留默认值)。

Implement willDisplayHeaderView, like so:

实现 willDisplayHeaderView,如下所示:

  override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    if let view = view as? UITableViewHeaderFooterView {
      view.backgroundView?.backgroundColor = UIColor.blueColor()
      view.textLabel!.backgroundColor = UIColor.clearColor()
      view.textLabel!.textColor = UIColor.whiteColor()
      view.textLabel!.font = UIFont.boldSystemFontOfSize(15)
    }
  }

Remember: If you're using static cells, the first section header is padded higher than other section headers due to the top of the UITableView; to fix this:

请记住:如果您使用的是静态单元格,由于 UITableView 的顶部,第一个部分标题会比其他部分标题填充得更高;解决这个问题:

Implement heightForHeaderInSection, like so:

实现 heightForHeaderInSection,像这样:

  override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    return 30.0 // Or whatever height you want!
  }

回答by Giorgio

Swift 4version of Leo Natan answeris

Swift 4版本的 Leo Natan答案

UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 28)

If you wanted to set a custom font you could use

如果你想设置一个自定义字体,你可以使用

if let font = UIFont(name: "font-name", size: 12) {
    UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = font
}

回答by Anup Gupta

With this method you can set font size, font style and Header backgroundalso. there are have 2 method for this

使用此方法,您还可以设置字体大小、字体样式和页眉背景。有两种方法可以做到这一点

First Method

第一种方法

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
        UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
        header.backgroundView.backgroundColor = [UIColor darkGrayColor];
        header.textLabel.font=[UIFont fontWithName:@"Open Sans-Regular" size:12];
        [header.textLabel setTextColor:[UIColor whiteColor]];
    }

Second Method

第二种方法

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
//    myLabel.frame = CGRectMake(20, 8, 320, 20);
    myLabel.font = [UIFont fontWithName:@"Open Sans-Regular" size:12];
    myLabel.text = [NSString stringWithFormat:@"   %@",[self tableView:FilterSearchTable titleForHeaderInSection:section]];

    myLabel.backgroundColor=[UIColor blueColor];
    myLabel.textColor=[UIColor whiteColor];
    UIView *headerView = [[UIView alloc] init];
    [headerView addSubview:myLabel];
    return headerView;
}

回答by Juan Boero

Swift 2:

斯威夫特 2:

As OP asked, onlyadjust the size, not setting it as a system bold font or whatever:

正如 OP 所要求的,调整大小,而不是将其设置为系统粗体字体或其他任何内容:

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if let headerView = view as? UITableViewHeaderFooterView, textLabel = headerView.textLabel {

            let newSize = CGFloat(16)
            let fontName = textLabel.font.fontName
            textLabel.font = UIFont(name: fontName, size: newSize)
        }
    }

回答by JerryH

This is my solution with swift 5.

这是我使用 swift 5 的解决方案。

To fully control the header section view, you need to use the tableView(:viewForHeaderInsection::) method in your controller, as the previous post showed. However, there is a further step: to improve performance, apple recommend not generate a new view every time but to re-use the header view, just like reuse table cell. This is by method tableView.dequeueReusableHeaderFooterView(withIdentifier: ). But the problem I had is once you start to use this re-use function, the font won't function as expected. Other things like color, alignment all fine but just font. There are some discussions but I made it work like the following.

要完全控制标题部分视图,您需要在控制器中使用 tableView(:viewForHeaderInsection::) 方法,如上一篇文章所示。但是,还有更进一步的步骤:为了提高性能,苹果建议不要每次都生成一个新视图,而是重复使用标题视图,就像重用表格单元格一样。这是通过 tableView.dequeueReusableHeaderFooterView(withIdentifier: ) 方法实现的。但是我遇到的问题是,一旦您开始使用此重用功能,字体将无法按预期运行。其他的东西,比如颜色,对齐都很好,但只是字体。有一些讨论,但我让它像下面这样工作。

The problem is tableView.dequeueReusableHeaderFooterView(withIdentifier:) is not like tableView.dequeneReuseCell(:) which always returns a cell. The former will return a nil if no one available. Even if it returns a reuse header view, it is not your original class type, but a UITableHeaderFooterView. So you need to do the judgement and act according in your own code. Basically, if it is nil, get a brand new header view. If not nil, force to cast so you can control.

问题是 tableView.dequeueReusableHeaderFooterView(withIdentifier:) 不像 tableView.dequeneReuseCell(:) 总是返回一个单元格。如果没有可用的,前者将返回一个 nil。即使它返回一个重用的头视图,它也不是你原来的类类型,而是一个 UITableHeaderFooterView。所以你需要在你自己的代码中做判断和行动。基本上,如果它为零,则获得一个全新的标题视图。如果不是零,强制施放,以便您可以控制。

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let reuse_header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "yourHeaderID")
        if (reuse_header == nil) {
            let new_sec_header = YourTableHeaderViewClass(reuseIdentifier:"yourHeaderID")
            new_section_header.label.text="yourHeaderString"
            //do whatever to set color. alignment, etc to the label view property
            //note: the label property here should be your custom label view. Not the build-in labelView. This way you have total control.
            return new_section_header
        }
        else {
            let new_section_header = reuse_section_header as! yourTableHeaderViewClass
            new_sec_header.label.text="yourHeaderString"
            //do whatever color, alignment, etc to the label property
            return new_sec_header}

    }