Reputation: 33
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?
Upvotes: 2
Views: 4611
Reputation: 1112
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
And the same approach works for UITableViewController
class BackgroundTableView: UITableView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
[....]
Upvotes: 0
Reputation: 38833
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
.
Upvotes: 3
Reputation: 54755
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.
Upvotes: 4