view.traitCollection.horizontalSizeClass returning undefined (0) in viewDidLoad

You will be better off moving that code to the viewWillAppear method, as in the viewDidLoad the ViewController's view has not been added to the hierarchy yet, and you might get an empty trait collection.


The problem is that viewDidLoad is too soon to be asking about a view's trait collection. This is because the trait collection of a view is a feature acquired from the view hierarchy, the environment in which it finds itself. But in viewDidLoad, the view has no environment: it is not in in the view hierarchy yet. It has loaded, meaning that it exists: the view controller now has a view. But it has not been put into the interface yet, and it will not be put into the interface until viewDidAppear:, which comes later in the sequence of events.

However, the view controller also has a trait collection, and it does have an environment: by the time viewDidLoad is called, the view controller is part of the view controller hierarchy. Therefore the simplest (and correct) solution is to ask for the traitCollection of self, not of view. Just say self.traitCollection where you now have view.traitCollection, and all will be well.

(Your solution, asking the screen for its trait collection, may happen to work, but it is not reliable and is not the correct approach. This is because it is possible for the parent view controller to alter the trait collection of its child, and if you bypass the correct approach and ask the screen, directly, you will fail to get the correct trait collection.)


I found that if I use the main screen's traitCollection, instead of the current view, I get the correct size class:

if (UIScreen.main.traitCollection.horizontalSizeClass == .compact) {
    fontSize = "20"
} else {
    fontSize = "28"
}

Tags:

Ios

Swift