Instruction 2

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

AnyLayout works great. It handles the changes for you and arranges the views in the correct way. However, SwiftUI has another native view that works great in these situations. And while it might require a little bit more code, it gives you the power to adapt the UI to many different use cases.

Using ViewThatFits

ViewThatFits is a SwiftUI view that allows you to pass many different views, of different sizes, that can be used in different contexts, and it will take all those views and decide which one fits best with the available space.

ViewThatFits {
  ReallyBigView()
  RegularSizeView()
  SmallView()
  TinyView()
}
ViewThatFits(in: .vertical) {
  LargeHorizontalView()
  LargeVerticalView()
}

Limitations

While AnyLayout seems simpler and with less code compared to ViewThatFits, it also requires you to write more code if you need to alternate over multiple different layouts. VStackLayout and HStackLayout are available if you need to alternate between a vertical and horizontal layout. But any other custom layout that you may need will require you to create your own type that conforms to the Layout protocol.

Using ViewThatFits for Accessibility

In the previous lesson, you learned about the importance of accessible UI and its importance to build apps that are inclusive. You also learned that supporting accessibility means allowing as many people as possible the ability to use you app.

@Environment(\.dynamicTypeSize) var dynamicTypeSize

var body: some View {
  switch dynamicTypeSize {
    case .accessibility1, 
      .accessibility2,
      .accessibility3,
      .accessibility4, 
      .accessibility5:
      AdaptedView()
    case .medium, 
      .small,
      .xSmall:
      ViewWithMoreContent()
    default:
      ViewAdaptedForLargeFonts()
  }
}
var body: some View {
  ViewThatFits {
    ViewWithMoreContent()
    ViewAdaptedForLargeFonts()
    AdaptedView()
  }
}
See forum comments
Download course materials from Github
Previous: Demo 1 Next: Demo 2