2

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?

nhgrif
  • 61,578
  • 25
  • 134
  • 173
user3110353
  • 512
  • 2
  • 7
  • 17

4 Answers4

5

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!

Justin Rose
  • 1,041
  • 7
  • 14
  • 1
    I think this is the best solution. This solution is especially convenient for other UIKit classes like `UIColor`, where we're already used to things like `UIColor.blackColor()`, for example. No way to add custom colors like that without extensions. – nhgrif Jun 22 '15 at 12:19
4

Its should be called like this

let fonts =  FontHelper().defaultFont(mySize)
Ankit Sachan
  • 7,690
  • 16
  • 63
  • 98
  • While this answer solves the problem, I think I much prefer Justin Rose's answer regarding using extensions. It's much nicer. Also, I think we could probably just declare the struct's method as being `static`, which would also be preferred to this. We really don't have to instantiate the struct.... but +1 anyway. – nhgrif Jun 22 '15 at 12:22
1

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.

Pradumna Patil
  • 2,180
  • 3
  • 17
  • 46
Sapana Ranipa
  • 889
  • 7
  • 20
0

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)
}
pableiros
  • 14,932
  • 12
  • 99
  • 105