如何在UITableView中设置Section属性?

时间:2015-01-04 13:34:44

标签: swift uikit

背景

我想在UITabelLabelCell中设置Section属性。

原始帖子,过时的Obj-C代码/方法

这是在UITable中设置节标题字体的代码。我试图在iOS7 +上使用此代码。

Obj-C代码

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

我认为它应该看起来像这样(不确定):

UILabel.appearanceForTraitCollection( trait: UITraitCollection )

但我在转录UITraitCollection时遇到了问题。

1 个答案:

答案 0 :(得分:5)

编辑:适用于iOS7 +的最佳解决方案

在UITableViewDelegate中实现tableView方法:

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

        // Background color
        view.tintColor = UIColor.blackColor()

        // Text Color/Font
        let header = view as UITableViewHeaderFooterView
        header.textLabel.textColor = UIColor.greenColor()
        header.textLabel.font = my_font // put the font you want here...
    }

以下的原始帖子(过时的hacky解决方案)

<强>研究

搜索关于该主题的很少的Apple文档和SO Q&amp; A,我无法弄清楚如何使用UITraitCollection

但是,我似乎在this post in SO找到了可能的黑客。

我已经使用下面的实现对其进行了测试,它似乎有用。

我们需要采取三个步骤来创建一个Objective-C类方法来完成这项工作。使用桥接头,我们可以从Swift无缝调用该方法。

添加到桥接标题

#import "BridgeAppearance.h"

创建BridgeAppearance.h

@interface BridgeAppearance : NSObject { }

+ (void)setFontForUITableHeaderFooters: (UIFont*)font;

@end

创建BridgeAppearance.m

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "BridgeAppearance.h"

@implementation BridgeAppearance

+ (void)setFontForUITableHeaderFooters: (UIFont*)font
{
    [[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil]
     setFont: font];
}

@end