I\'m using a UITextView inside a UIPageViewController, and I want to determine the font size based on the size class of the device.
The first slide of the page view is l
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.
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"
}
I took a hint from this Apple Technical Q&A and used viewWillLayoutSubviews
instead of viewDidLoad
/viewWillAppear
.
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.)
In my case I needed my view to know about the horizontalSizeClass so accessing the UIScreen traitCollection was tempting but not encouraged, so I had something like this:
override func layoutSubviews() {
super.layoutSubviews()
print("\(self.traitCollection.horizontalSizeClass.rawValue)")
switch self.traitCollection.horizontalSizeClass {
case .regular, .unspecified:
fontSize = 28
case .compact:
fontSize = 20
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
print("\(self.traitCollection.horizontalSizeClass.rawValue)")
guard let previousTraitCollection = previousTraitCollection else { return }
if self.traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass {
layoutIfNeeded()
}
}