How to observe observe changes in screen size in Swift
A step by step guide on observing when the view controller's view's size changes in Swift.
The following tutorial uses our Open Source Swift project to walk you through how to detect when the view controller's view's size changes on iPhone, iPad or Mac.
This tutorial also works to register changes in orientation, however if you are looking for a tutorial that focuses specifically on a way to do that without screen size changes, please consult the tutorial below.
We recommend that you clone our Open Source Swift Starter Project, checking out the main branch and carrying out the steps below. The changes can be found on the tutorial/view-transitions branch.
git clone firstname.lastname@example.org:delasign/swift-starter-project.git
Step One: Add the viewWillTransitionToSize function
In ViewController.swift, or your chosen ViewController, add the viewWillTransitionToSize function using code similar to the one below.
Step Two: Verify
Run the app in XCode on an iPhone, iPad or Mac and change the orientation or screen size and you will see the console display the frame and orientation.