2

I'd like to override preferredStatusBarStyle in an extension of UIViewController like this:

extension UIViewController {
    open override var preferredStatusBarStyle: UIStatusBarStyle {
      return .lightContent
    }
}

The compiler throws this error Getter for 'preferredStatusBarStyle' with Objective-C selector 'preferredStatusBarStyle' conflicts with method 'preferredStatusBarStyle()' with the same Objective-C selector

Applying the same override to UINavigationController instead of UIViewController works; but preferredStatusBarStyle is a var that is inherited by UIViewController.

-> Why is it possible to apply this extension to UINavigationController but not to UIViewController

benrudhart
  • 1,406
  • 2
  • 13
  • 25

1 Answers1

5

You can't override (re-declare implementation of) already implemented properties this way via extensions in Swift on a class which introduces the property.

You should definitely create a UIViewController subclass and use it app-wide instead.

There's an option, however. You can override this using Objective-C by providing an extending category, similar thing applied to UIFont answered here: Is there a way to change default font for your application. However, it's not completely safe to do so and you should expect unicorns to come when not careful enough.

Community
  • 1
  • 1
Michi
  • 1,464
  • 12
  • 15
  • 1
    Thank you michi. I don't like the idea of having my custom base class of UIViewController, hence I'd have to implement this in every UIViewController class again and again... – benrudhart Mar 06 '17 at 06:49
  • No you wouldn't, all you need to do is inherit all other controllers from `MyBaseViewController` instead of `UIViewController` and implement the generic stuff in your `MyBaseViewController`. This is probably a recommended way. – Michi Mar 06 '17 at 10:11
  • 2
    That is exactly what I had in mind when I said "I don't like the idea of having my custom base class of UIViewController" – benrudhart Mar 06 '17 at 10:50