Instruction 1

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

The Problem with View Identity

Back to the basics of SwiftUI, the framework uses view identity to tag a view for redrawing, should its data dependencies change. It’s important to understand this because a view might not behave like you expect it to because it’s being re-rendered or completely replaced by another view.

if isRedColor {
  Text("RGB Picker")
    .foregroundStyle(.red)
} else {
  Text("RGB Picker")
    .foregroundStyle(.blue)
}
Text("RGB Picker")
  .foregroundStyle(isRedColor ? .red : .blue)

Using AnyLayout to Switch Between Different Layouts

AnyLayout is a type that conforms to the new Layout protocol. You can use this type to change the arrangement of the subviews in the container view, without destroying the underlying views.

let layout = landscapeIsCompact ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())
layout {
  Text("Hello")
  Text("World")
}

The New Layout Protocol

iOS 16 introduced the new Layout protocol. This protocol allows you to create types that build more complex custom container layouts. While most UI can be achieved with a combination of native SwiftUI views, like VStack and HStack, you might find yourself needing to implement something that is completely new and different from what you see elsewhere.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo 1