Reputation: 522
I have a UIFont Class that looks like this:
struct FontHelper {
func defaultFont(size: CGFloat) -> UIFont {
return UIFont(name:"Helvetica", size: size)!
}
}
and I call the method like this"
let fonts = FontHelper.defaultFont(12)
However my app crashes with an unexpected found nil while wrapping optional?
Have no idea why?
Upvotes: 2
Views: 1249
Reputation: 16042
If you add custom fonts manually to your project, you need to register the fonts before use it in runtime:
func loadFont(withName fontName: String) {
guard let fontURL = Bundle.main.url(forResource: fontName, withExtension: "ttf"),
let fontData = try? Data(contentsOf: fontURL) as CFData,
let provider = CGDataProvider(data: fontData),
let font = CGFont(provider) else { return }
CTFontManagerRegisterGraphicsFont(font, nil)
}
// For example, this array need to contain the fonts filenames without extension.
let fontNames = ["Roboto-Black", "Roboto-Regular", "Roboto-Bold"]
for fontName in fontNames {
loadFont(withName: fontName)
}
Upvotes: 0
Reputation: 919
When u work with UIFont(name:"HelveticaCE-Regular", size:14.0)
I believe iOS requires the PostScript name for a font when using fontWithName: size:
, which you can find/verify by opening the font in Apple's Font Book and typing command+I.
Maybe this helps you.
Upvotes: 1
Reputation: 1041
Since you're adding your own personal functionality to a Type, I think you should use an extension, declare this extension outside of your class:
extension UIFont {
// You can set a default value for the size if the user doesn't provide one.
class func defaultFont(_ size: CGFloat = 12) -> UIFont {
return UIFont(name:"Helvetica", size: size)!
}
}
Now, the UIFont Type has this really cool functionality you just added.
Within your class, call it:
let font = UIFont.defaultFont(12)
I hope you can see the power of extensions here, so take advantage of them in Swift!
Upvotes: 5
Reputation: 7850
Its should be called like this
let fonts = FontHelper().defaultFont(mySize)
Upvotes: 4