SwiftUI Views & Layouts

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

Lesson 03: Building Views

Demo 1

Episode complete

Play next episode

Next
Transcript

To use AnyLayout, you’ll reuse most of the code of the current iteration. The difference is that instead of using the vertical and horizontal size classes and landscapeIsCompact to switch between VStack and HStack, you’ll define the layout of AnyLayout and it will switch between the two for you.

To start, open ContentView.swift and add the following computed property:

var layout: AnyLayout {
  landscapeIsCompact ?
    AnyLayout(HStackLayout(spacing: 16)) :
    AnyLayout(VStackLayout(spacing: 16))
}

Here, you’re using landscapeIsCompact to decide if the elements should be displayed in a horizontal layout or vertical layout. The difference is that instead of switching between HStack and VStack, you use AnyLayout with either HStackLayout or VStackLayout. AnyLayout will use this to arrange its subviews in a vertical or horizontal fashion.

Next, replace the contents of the body with the following:

layout {
  ColorCardView(color: color)

  RGBSlidersStackView(
    color: $color,
    red: $red,
    green: $green,
    blue: $blue
  )
}
.padding()

Here, much like a VStack or HStack, you’re using the layout as a container and passing ColorCardView and RGBSlidersStackView as subviews of it. AnyLayout takes those views and uses the correct layout depending on landscapeIsCompact to arrange them.

If landscapeIsCompact is true, layout will use HStackLayout and arrange the views horizontally. However, if landscapeIsCompact is false, it’ll use VStackLayout and arrange the views vertically.

Build and run the project. Rotate the simulator to check if the layout still adapts to the landscape orientation.

You’ll notice not much has changed. When you rotate the device to landscape orientation, the screen rotates and the iOS animates and arranges the view a horizontal layout. That’s because when the orientation changes, iOS already applies a default animation.

But while the final result looks very similar to the UI you had before, the amount of code to achieve this and switch between a vertical and horizontal layout is so much cleaner.

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