UIAppearance Swift 4

Eli Whittle picture Eli Whittle · Jul 17, 2017 · Viewed 11.3k times · Source

After updating to Swift 4, I am getting a compiler error:

Static member 'appearance' cannot be used on protocol metatype 'UIAppearance.Protocol'

Here is my viewWillAppear method in my custom Tab Bar Controller subclass, I am setting the font of the item text.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // compiler error on line below
    UIAppearance.appearance().setTitleTextAttributes([NSAttributedStringKey.font: font], for: UIControlState.normal)
}

I'm having trouble fixing this, any guidance would be appreciated, thanks!

Answer

Justin Whitney picture Justin Whitney · Jul 25, 2017

Right - the current Swift 4 conversion tool (as of Xcode 9 Beta 4) gets a little carried away.

I was able to fix the problem quickly by reverting the UIAppearance conversion code, then updating the individual attributes.

For example, in Swift 3 I had:

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .selected)

Xcode "helped" me out by changing it to:

UIAppearance.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white], for: .selected)

I was able to quiet the errors by half-reverting, to:

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white], for: .selected)