0

I am trying to add Custom Fonts in Xcode 10 & I keep getting this error:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

  • I have included the fonts in my Info.plist
  • I have checked my "Copy Bundle Resources" & It is there.

I still get this error.

This my code below:

DispatchQueue.main.async {
    let paragraph = NSMutableParagraphStyle()
    paragraph.alignment = .center

    let attributedString = NSAttributedString(string: message, attributes:
        [.paragraphStyle: paragraph, NSAttributedString.Key.font : UIFont (name: "Lato-Regular", size: 14)!]) // Throws error here

    let alert = UIAlertController(title: title, message: "", preferredStyle: .alert)
    alert.setValue(attributedString, forKey: "attributedMessage")

    alert.addAction(UIAlertAction(title: "Back", style: .cancel, handler: nil))
    self.present(alert, animated: true)
}

Throws Error on this line

UIFont (name: "Lato-Regular", size: 14)!

Xcode cannot find font, but I can also use the font on the Storyboard UI. So how come?

Cœur
  • 37,241
  • 25
  • 195
  • 267
truthsayer
  • 397
  • 2
  • 8
  • 22

1 Answers1

0

UIFont.familyNames will give you a list of all available font families. UIFont.fontNames(forFamilyName:) will give you all font names. Use that to find out the correct name of your font.

let families = UIFont.familyNames
let allFonts = families.flatMap { UIFont.fontNames(forFamilyName:$0) }
let latoFonts = allFonts.filter { $0.contains("Lato") }
print(latoFonts)

orkoden
  • 18,946
  • 4
  • 59
  • 50