How to make system font "Black Italic" in swift?

Viewed 4345

I am trying to add a system font of weight "Heavy" (not bold) and also try to make it italic. I saw other stackoverflow solutions but it does not seem to work. Here is what I have done:

let percentageLabel: UILabel = {
       let label = UILabel()
        label.text = "0"
        label.textAlignment = .center
        label.textColor = .white
        label.font = UIFont.systemFont(ofSize: 32, weight: .heavy, traits: .traitItalic)
       return label
    }()

Extension as suggested in a stack overflow post

extension UIFont {

    static func systemFont(ofSize: CGFloat, weight: UIFont.Weight, traits: UIFontDescriptor.SymbolicTraits) -> UIFont? {
         let font = UIFont.systemFont(ofSize: ofSize, weight: weight)

         if let descriptor = font.fontDescriptor.withSymbolicTraits(traits) {
             return UIFont(descriptor: descriptor, size: ofSize)
         }

         return nil
     }
}

Thing is when I tried all suggested solutions, bold and italic seems to work BUT black and italic doesn't work. It is still rendered as regular italic.

3 Answers

Swift 5.*

extension UIFont {
      
    class func italicSystemFont(ofSize size: CGFloat, weight: UIFont.Weight = .regular)-> UIFont {
        let font = UIFont.systemFont(ofSize: size, weight: weight)
        switch weight {
        case .ultraLight, .light, .thin, .regular:
            return font.withTraits(.traitItalic, ofSize: size)
        case .medium, .semibold, .bold, .heavy, .black:
            return font.withTraits(.traitBold, .traitItalic, ofSize: size)
        default:
            return UIFont.italicSystemFont(ofSize: size)
        }
     }
    
     func withTraits(_ traits: UIFontDescriptor.SymbolicTraits..., ofSize size: CGFloat) -> UIFont {
        let descriptor = self.fontDescriptor
            .withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits))
        return UIFont(descriptor: descriptor!, size: size)
     }
      
}

Usage:

myLabel.font = UIFont.italicSystemFont(ofSize: 34, weight: .black)

Try this

     label.font = UIFont.systemFont(ofSize: 32, weight: .black, traits: .traitItalic)
//If you just want Italic then use this
   labelInfo.font = UIFont.italicSystemFont(ofSize: 32)

Swift 5.0

extension UIFont {
    static func systemFontItalic(size fontSize: CGFloat = 17.0, fontWeight: UIFont.Weight = .regular) -> UIFont {
        let font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
        return UIFont(descriptor: font.fontDescriptor.withSymbolicTraits(.traitItalic)!, size: fontSize)
    }
}

Usage:

label.font = UIFont.systemFontItalic(size: 20.0, fontWeight: .black)

Output:

enter image description here

Related