
SwiftUI small tricks: improve your layout on landscape iPhone with size classes
- Published
When building for iOS and the Apple ecosystem in mind, it’s the littlest of changes that can make the difference between a good app and a truly great app. The name of the game is: making your app looks its best self on every screen and every screen orientation. You could wrap everything in a GeometryReader and rely on a fully custom layout, but if you’re looking for a native SwiftUI way to improve your app in a matter of minutes: the horizontalSizeClass and verticalSizeClass values are the way to go.
The basics of UserInterfaceSizeClass
You can access them as environment values in your views:
struct MyView: View {
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
@Environment(\.verticalSizeClass) private var verticalSizeClassThe value conforms to the UserInterfaceSizeClass enum. It returns either .regular, .compact. It is optional, and updated in real-time.
verticalSizeClass: when screen height comes as a rare resource
The lack of vertical space on iPhones in landscape mode is not easy to work with as a dev. For this reason, I found out most developers don’t really give their best try; they either just let their portrait experience show up as-is in landscape mode, or they block landscape mode on phones entirely. This creates friction, as the end user has to rotate their phone to use the app “they way the dev intended”…
verticalSizeClass is an easy quick fix for most of your views. On everyday life scenarios, it switches to .compact only on iPhone in landscape mode.
For this example, let’s assume a simple list of contacts, with a ContactRow component.
List(contacts) { contact in
ContactRow(contact)
}You’ll want your component to automatically switch to a compact mode, when the vertical display is compact.
struct ContactRow: View {
@Environment(\.verticalSizeClass) private var verticalSizeClass
let contact: Contact
var body: some View {
if verticalSizeClass == .compact {
compactLayout
} else {
fullLayout
}
}
// layouts can then come here
}Here’s the result, applied to my app RelCheck: a compact list that works with the tiny space it has, by making use of the extra horizontal space and displaying all information in one line instead of two.

Next time…
Next time, we’ll see about horizontalSizeClass specifically: its real-life scenarios and use cases, and how it could be used to improve your app.