NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to create views in a loop using ForEach   How to place content outside the safe area >

How to create different layouts using size classes

SwiftUI supports size classes natively by exposing them in the environment for us to read. To use them, first create an @Environment object that will store its value, like this:

@Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?

Then you check the value of that property whenever you need, looking for either the .compact or .regular size class, like this:

if horizontalSizeClass == .compact {
    return Text("Compact")
} else {
    return Text("Regular")
}

Putting all that together, you might create a view like this:

struct ContentView : View {
    @Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?

    var body: some View {
        if horizontalSizeClass == .compact {
            return Text("Compact")
        } else {
            return Text("Regular")
        }
    }
}

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to create views in a loop using ForEach   How to place content outside the safe area >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 3.6/5

Click here to visit the Hacking with Swift store >>