How do I create a bold UIFont from a regular UIFont?

后端 未结 7 1904
醉话见心
醉话见心 2020-12-08 19:08

If I have a UIFont object, is it possible to convert it to bold? I don\'t know the font name, I just have a UIFont object. What I want is a function like

<
7条回答
  •  执笔经年
    2020-12-08 19:48

    Since this question pops up when you search for bold UIFonts in Swift, here's a fresh answer:

    extension UIFont {
        /// Returns a new font in the same family with the given symbolic traits,
        /// or `nil` if none found in the system.
        func withSymbolicTraits(_ traits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
            guard let descriptorWithTraits = fontDescriptor.withSymbolicTraits(traits)
                else { return nil }
            return UIFont(descriptor: descriptorWithTraits, size: 0)
        }
    }
    

    Example:

    myFont.withSymbolicTraits(.taitBold) // returns the bold version of myFont
    

提交回复
热议问题