How to set backgroundColor of a ViewController with UIAppearance

4.3k views Asked by At

I'm trying to use UIAppearance to configure the style of my Apps. It works perfectly with the UI components like UIView or UIButton, but it doesn't with UIViewControllers. I would like to do something like:

let appearance = FirstViewController.appearance()

Is there a way to use UIAppearance with ViewControllers?

3

There are 3 answers

4
Rashwan L On

You don´t set the background color in a viewController you do set it on the viewControllers view. If you use UIView.appearance().backgroundColor you will change the background of all views.

So the answer to your question is no you can´t use UIAppearance to change the viewControllers background color.

What you could do is the following:

class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
    }
}

Then use the inspector in your Storyboard to change UIViewController to FirstViewController.

0
Dávid Pásztor On

As you can see in the documentation of the UIAppearance protocol, only two classes adopt it by default, UIView and UIBarItem, hence the UIViewController class has no appearance() function.

You can either extend UIViewController by implementing the required methods of the protocol, or probably an even easier solution would be to create your own UIViewController subclass, which provides a default color for the classes view.backgroundColor property and make all your ViewControllers inherit from this class instead of UIViewController directly.

0
Lveecode On

As previous answers have pointed out, there's no way to change UIViewController's root view background through UIAppearance protocol. But there are ways to achieve the same result without the need to have a root UIViewController subclass inherited by all other ViewControllers, or setting the color in every UIViewController's viewDidLoad() (both approaches have their drawbacks)

Instead you can create a UIView subclass

class BackgroundView: UIView {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // Set your background color
        self.backgroundColor = .black

        // Or, if your background is an image
        self.layer.contents = UIImage(named: "background")!.cgImage
    }
}

In the storyboard, set your ViewController's root view class to this UIView subclass screenshot

And the same approach works for UITableViewController

class BackgroundTableView: UITableView {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
[....]

screenshot

screenshot