SwiftUI Views & Layouts

Jun 20 2024 · Swift 5.10, iOS 17.4, Xcode 15.3

Lesson 02: Configuring Layouts

Demo 1

Episode complete

Play next episode

Next
Transcript

Now that you know about the importance of landscape orientation, you’ll learn how to use Xcode Previews to preview your views in landscape and solve the problem of part of the layout being out of bounds.

Open ContentView.swift, compile and run the project. Now, click the top-right button on the simulator window. This button will rotate the device to the right.

You’ll see the problem of part of the content being out of bounds. You can still use the red and green sliders, but the blue slider and the button are unreachable.

Use a ScrollView to fix this. But first, add preview code to ContentView.swift to preview the layout in landscape.

Still in ContentView.swift, refresh Xcode Preview canvas by using the shortcut CMD+Option+P. On the bottom bar of the canvas, click the third button and select Orientation Variants.

This tells Xcode Previews that you want to preview this view in all orientation variants – including Portrait, Landscape Left and Landscape Right.

You can use this to preview your layout in the different orientation your app and device supports. You can also check out other variations of your view like Color Scheme and Dynamic Type.

Another way to preview UI in other orientations is to pass a trait parameter to the #Preview macro.

In the canvas, click the first button on the bottom to go back to preview mode. Next, scroll down to the bottom of the file and add the following code:

#Preview(traits: .landscapeLeft) {
  ContentView()
}

This adds an additional preview to the canvas of ContentView, with the trait of .landscapeleft. In the canvas, you’ll notice a new tab at the top.

Click the second tab and Xcode Previews shows ContentView on an iPhone in the left landscape orientation.

Now that you can check how your UI is working in landscape, it’s time to fix the content being out of bounds.

Right click the first VStack inside the body of ContentView, and select Embed…. Next, type ScrollView:

ScrollView {

This will embed the whole view hierarchy in a ScrollView. Refresh the canvas by using the shortcut Command-Option-P again, and check the landscape preview.

Great job! You can now scroll through the contents of the view and use all three sliders and button to set a color.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction 1 Next: Instruction 2