Swift - fontDescriptor returns NIL when making font to Italic in iOS 12

882 views Asked by At

I have been struggling for a while now about this fontDescriptor.withSymbolicTraits it returns nil whenever I try to use Bold or Italic.

I'm using this code below:

func withTraits(traits:UIFontDescriptor.SymbolicTraits) -> UIFont {
    let descriptor = fontDescriptor.withSymbolicTraits(traits)
    return UIFont(descriptor: descriptor!, size: 0) //size 0 means keep the size as it is }

func bold() -> UIFont {
    return withTraits(traits: .traitBold) }

func italic() -> UIFont {
    return withTraits(traits: .traitItalic) }

But the app stops and shows this error (this points to fontDescriptor.withSymbolicTraits):

Fatal error: Unexpectedly found nil while unwrapping an Optional value Fatal error: Unexpectedly found nil while unwrapping an Optional value

I also tried this code (which works on other devs as what I read online):

    var isBold: Bool {
        return fontDescriptor.symbolicTraits.contains(.traitBold)
    }

    var isItalic: Bool {
        return fontDescriptor.symbolicTraits.contains(.traitItalic)
    }

    func setBoldFnc() -> UIFont {
        if(isBold) {
            return self
        } else {
            var fontAtrAry = fontDescriptor.symbolicTraits
            fontAtrAry.insert([.traitBold])
            guard let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry) else { return self }
            return UIFont(descriptor: fontAtrDetails, size: 0)
        }
    }

    func setItalicFnc()-> UIFont {
        if(isItalic) {
            return self
        } else {
            var fontAtrAry = fontDescriptor.symbolicTraits
            fontAtrAry.insert([.traitItalic])
            guard let fontAtrDetails = fontDescriptor.withSymbolicTraits(fontAtrAry) else { return self }
            return UIFont(descriptor: fontAtrDetails, size: 0)
        }
    }

Anyone out there experiencing this in iOS 12 onwards?

I also read that there was a bug in iOS 8 regarding this, but says that this was fixed in the later version already:

https://code-examples.net/en/q/18c6177

Font Descriptor returns nil in iOS 8

*NOTE: I used custom font with only "-Regular" file. 'Cause some font doesn't have "-Italic" or "-Bold" font style.

Example: Archivo Black font and Oswald font

0

There are 0 answers