Size classes are natively supported by SwiftUI, which exposes them for us to read in the environment. Use them by first creating a @Environment object that will hold its value, then looking for the .compact or .regular size class and checking the value of that property whenever necessary.
For example:
struct ContentView: View {
@Environment(\.horizontalSizeClass) var horizontalSizeClass
var body: some View {
if horizontalSizeClass == .compact {
Text("Compact")
} else {
Text("Regular")
}
}
}
When you utilize a VStack or an HStack for your content, size classes are a terrific approach to make your user interfaces intelligently adjust to the available space.
For instance, you might arrange things horizontally if you have a lot of room, but when you don’t, you will move to a vertical arrangement.
Using the @Environment property wrapper, SwiftUI offers a convenient way to read values stored in the EnvironmentValues structure.
For example, by providing the path to the verticalSizeClass key, we can retrieve the vertical size class of the user interface. Depending on the device type and orientation, the UserInterfaceSizeClass value stored in this property tells our view how much vertical space is available. By considering variables such as whether the device is in portrait or landscape mode and whether the screen size is an iPhone, iPad, or other display, SwiftUI automatically determines this value.
For example:
struct ContentView: View {
@Environment(\.verticalSizeClass)
private var verticalSizeClass
var body: some View {
VStack {
Text("Hello Developers!")
.font(.largeTitle)
if verticalSizeClass == .regular {
Text("Developers")
.font(.system(size: 30))
.fontWeight(.heavy)
Image("developers")
}
if verticalSizeClass == .compact {
Text("SwiftUI Apps")
.font(.system(size: 30))
.fontWeight(.heavy)
Image("apps")
.resizable()
.scaledToFit()
}
}
.padding()
}
}
In this example, we check the vertical and horizontal size classes to determine if the view has enough vertical space to display one image or another depending on the device’s position. If the size class is regular, the text “Developers” will appear, while if it’s compact, the text “SwiftUI Apps” will appear.

