iPad Development Notes
Recently at work we started working on making the existing iPhone app work universally on iPad as well. Here some notes I came up with that seemed helpful...
The Apple docs here are also useful
userInterfaceIdiom #
Don't use UIDevice.current.userInterfaceIdiom
, as checking the device will break when the user has the app open on the side.
Size classes #
Use size classes instead of userInterfaceIdiom. You can think of horizontalSizeClass == .regular
as being equivalent to UIDevice.current.userInterfaceIdiom == .pad
and horizontalSizeClass == .compact
as being equivalent to UIDevice.current.userInterfaceIdiom == .phone
but have the benefit of working with split view.
Size classes are part of the trait collection, in a trait environment (UIView, UIViewController, UIPresentationController) so you can access it in the traitCollection
property and can be notified when it changes by overriding the traitCollectionDidChange(_:)
method.
UIScreen also conforms to UITraitEnvironment but you should use the trait environment furthest down the view hierarchy you can. If the view/view controller is in a popover or split view controller then the horizontal size can be compact even when the app’s UIScreen horizontal size class is regular.
See the WWDC 14 video Building Adaptive Apps with UIKit
Interface builder #
• Use Interface Builders's ability to Vary traits instead of creating constraints in code, or connecting them to IBOutlets. Most of the time you can click the vary traits button in interface build, select Introduce variations by width, and select an iPad. You can then add constraints and it will only affect the layout when the size class is regular. You can also alter some properties in the inspector by clicking the little plus button next to them. To remove a constraint while Varying click the plus button next to the enabled property and untick it for that size class. Then you can click Done Varying and change the device to see the different layouts. https://help.apple.com/xcode/mac/10.2/index.html?localePath=en.lproj#/dev8181af7e6
Readable content guide #
If the designs look like the width of something should be proportional to the width (by about 70%) instead try to use the readableContentGuide.
The readable content guide will automatically adapt to the width of the app and will increase if users chooses a larger font size.
To do this in Interface Builder:
- Change the trailing and leading constraints to left and right constraints
- Set the left and right constraints to “Relative to margin”
- Set the constants to 0 and remember them.
- In the superview go to the Size Inspector
- Set the margins to “Fixed” and in the left and right margin enter the constants from step 3.
- Tick the “Follow Readable Width” box
We have to use fixed margins instead of directional margins as directional margins in interface builder aren’t supported on iOS 10, and will cause the app to crash.