Fix for 'navFont can't be used on instance...'

I have a file called CustomAppearances.swift that works with Custom Appearances. In it, I have this code:

import Foundation
/*
Custom Appearance structure. Contains all attributes and methods required to apply custom appearance who are not related to a component or a class.

- parameter navFont: The font style used in the navigation bar title
*/
struct CustomAppearance {
  
    static let navFont = UIFont(name: "SF-UI-Text-Light", size: 17.0)
  
           func applyCustomAppearanceToNavigationBar() {
        UINavigationBar.appearance().translucent = false
        UINavigationBar.appearance().barTintColor = UIColor.whiteColor()
        UINavigationBar.appearance().tintColor = UIColor.blackColor()
        UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: navFont!, NSForegroundColorAttributeName: UIColor.blackColor() ]
    }
  
}

I get an error that says "navFont can't be used on instance of type 'Custom Appearances.'"

Is there a fix for this? This is the app I was planning on submitting with my WWDC scholarship application.



Thanks.

It's a Swift quirk that you cannot use a class member without writing out the class, so you need:


UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: CustomAppearance.navFont!, NSForegroundColorAttributeName: UIColor.blackColor() ]


The "instance of type 'CustomAppearance'" referred to in the error message is the implied self, as if you wrote "self.navFont".


Incidentally, I'd recommend you do this:


static let navFont = UIFont(name: "SF-UI-Text-Light", size: 17.0)!


instead of unwrapping with a "!" when you use 'navFont'. It avoids the implict check-for-nil at every reference, and it will cause your app to crash earlier, making it clearer what went wrong, if the font isn't available.


Edit: added a missing "not" to the first sentence. Sorry, I seem to be having trouble with that word today.

It's a Swift quirk that you cannot use a class member without writing out the class …

The plan is to make that easier in Swift 3.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Fix for 'navFont can't be used on instance...'
 
 
Q