Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set system font for CATextLayer()?

For UILabel, I can set the system font as:

label.font = UIFont.systemFontOfSize(18, weight: UIFontWeightMedium)

For CATextLayer, is there a similar way to set the system font instead of giving the font name directly?

textLayer = CATextLayer() 
textLayer.font = ??? // instead of CTFontCreateWithName("HelveticaNeue-Bold", 18, nil)
like image 282
Joe Huang Avatar asked Feb 18 '16 01:02

Joe Huang


1 Answers

The answer is no, but if you are bored about type system font names, you can wrap in a simple function:

func CTFontCreateSystemFontWithSize(size: CGFloat) -> CTFontRef {
    return CTFontCreateWithName(UIFont.systemFontOfSize(1).fontName, size,  nil)
}

For custom fonts, I like to enumerate the font family like this:

enum MyFontFamily: String {
    case Thin = "MyFont-Thin"
    case Light = "MyFont-Light"
    case Medium = "MyFont-Medium"
    case Bold = "MyFont-Bold"

    func font (size: CGFloat) -> UIFont? {
        return UIFont(name: self.rawValue, size: size)
    }

    func CTFont (size: CGFloat) -> CTFontRef {
        return CTFontCreateWithName(self.rawValue, size, nil)
    }
}

The usage is very simple

textLayer.font = MyFontFamily.Medium.CTFont(18.0)

This is useful to keep everything typed strongly, so you will get autocompletion for free and avoid typos.

like image 125
Jan Cássio Avatar answered Nov 15 '22 06:11

Jan Cássio