Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a specific Size Class on a view

I have a view that needs different constraints between the iPad & iPhone version.

The login screen is presented as full screen on iPhone & in a page sheet on the iPad. Due to size the UITextFields are 40 pixels away from the right and left sides on the iPhone, but I want them to be 80 pixels on the iPad. I set this as a specific constraint for the Final Values Size Class (w Regular, h Regular).

However because this view appears on a page sheet it doesn't use the Final Values Size Class. Ideally I would like to "force" the view to use a size class, rather than having an array of iPhone/iPad constraints and lots of constraint Outlets.

like image 309
William Robinson Avatar asked Jan 08 '23 20:01

William Robinson


1 Answers

The way this is meant to be accomplished is with trait collections on UIViewController, easily by calling -setOverrideTraitCollection:forChildViewController:.

This means you will need to have your view here actually be an explicit child view controller, which has been the recommended practice for a while (and actually can be beneficial in other ways), and I think it might be automatic, but if not there are ways for the parent/child relationship to blend nicely with presenting/presented view controller relationship.

You will also need to make sure to create the trait collection correctly, which is described in the introduction in the UITraitCollection Class Reference

EDIT: This answer by Nick Lockwood, who wrote Core Animation Advanced Techniques, says "That's not how it's supposed to be used" BUT that answer is from 2012/iOS 5, and since then View Controller presentation has been streamlined and size classes (and the methods specifically to override them) have been introduced.

I think you could make the view controller a child and -setOverrideTraitCollection:forChildViewController: on it as or before you present it. In a worst case you could create a generic UIViewController, embed yours inside it as a child and present that. Let us know if any of these techniques work for you.

like image 172
Mike Sand Avatar answered Jan 17 '23 02:01

Mike Sand