0

Background

I would like to set Section attributes in an UITabelLabelCell.

Original Post with outdated Obj-C Code/approach Below

This is code to set the font for section headers within a UITable. I'm trying to adopt this code for iOS7+.

Obj-C Code

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

I think it should look something like this (not certain):

UILabel.appearanceForTraitCollection( trait: UITraitCollection )

but I'm having trouble transcribing the UITraitCollection.

kfmfe04
  • 14,936
  • 14
  • 74
  • 140
  • possible duplicate of [appearanceWhenContainedIn in swift](http://stackoverflow.com/questions/24136874/appearancewhencontainedin-in-swift) – akashivskyy Jan 04 '15 at 14:54

1 Answers1

5

Edit: Best Current Solution for iOS7+

Implement a tableView method in your UITableViewDelegate:

   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...
    }

ORIGINAL POST BELOW (outdated hacky solution)

Investigation

Searching around scant Apple docs on the subject and SO Q&A, I could not figure out how to use UITraitCollection.

However, I seem to have found a possible hack in this post in SO.

I have tested it with an implementation below and it seems to work.

We need to take three steps to create an Objective-C class method to do the job. Using bridging headers, we can seamlessly call the method from Swift.

Add to Bridging Header

#import "BridgeAppearance.h"

Create BridgeAppearance.h

@interface BridgeAppearance : NSObject { }

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

@end

Create 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
Community
  • 1
  • 1
kfmfe04
  • 14,936
  • 14
  • 74
  • 140