0

I have a screen in my app with multiple child view controllers. On smaller screen sizes like iPhone, the view controllers are placed flush against each other. On iPad screen sizes, one of the view controllers floats on top of the other.

I want to make it so my view controller that sometimes floats only has a corner radius when it's floating. Therefore, I've looked into overriding a method like viewDidLoad or overrideTraitCollection(forChildViewController:) in my child view controller to set the corner radius of its view based on whether its size class is wRegular,hRegular, which is for iPads in portrait or landscape.

However, the child view controller doesn't seem to have the same size class values set as the root view controller, and traveling up the parentViewController hierarchy doesn't seem to get me to a view controller that does have those values.

How should I access the current size class of the top of the view hierarchy from a child view controller?

edit: I've tried the existing answer using UIScreen, and it works great when my app is the only visible app. However, it results in incorrect behavior when the app is run in split screen mode-- it always returns Regular/Regular even if the app is narrow. Is there a solution that involves getting the size class for just the part of the screen my app is in?

Rikki Gibson
  • 4,136
  • 23
  • 34
  • 1
    "How should I access the current size class of the top of the view hierarchy from a child view controller?" Ask the screen what its size class is. – matt Aug 25 '16 at 04:06
  • That was it. Thanks! – Rikki Gibson Aug 25 '16 at 04:10
  • Here is a downloadable example project that shows you how to change the trait environment for a child. https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch06p321overrideTraitCollection/OverrideTraitCollection/ViewController.swift The example does exactly the sort of thing you describe: the child behaves differently when the trait collection is different (configured in the storyboard) – matt Aug 25 '16 at 04:11

1 Answers1

3

Like this (this is current Swift 3):

let tc = UIScreen.main.traitCollection

Now you can interrogate the vertical and horizontal size class of tc.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 2
    Although this is an option but not recommended if you supports iPad's multi-tasking. – tzuer Oct 01 '17 at 15:48
  • @user3049050 So the screen won't give the right answer for this app, when we're under iPad multitasking? – matt Oct 01 '17 at 16:44
  • Yep – UIScreen's traitCollection returns regular even resized in multi-task. Recommended to get the one from View Controller instead. – tzuer Oct 05 '17 at 20:52
  • @tzuer in that case I'd suggest the window. You can't get further up the view hierarchy than that, and there always _is_ a window. – matt Oct 05 '17 at 21:25