6

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)
1
  • Use CTFontCreateUIFontForLanguage and set CTFontUIFontType to System?
    – juniperi
    Commented Feb 18, 2016 at 2:08

1 Answer 1

11

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.