简体   繁体   中英

Custom font in Swift 5 not working in Xcode 10

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM