Alternative to switch statement in SwiftUI ViewBuilder block?

前端 未结 6 1575
耶瑟儿~
耶瑟儿~ 2020-12-02 12:21

⚠️ 23 June 2020 Edit: From Xcode 12, both switch and if let statements will be supported in the ViewBuilder!

I’ve been trying to replicate an app of

6条回答
  •  生来不讨喜
    2020-12-02 12:41

    Update: SwiftUI 2 now includes support for switch statements in function builders, https://github.com/apple/swift/pull/30174


    Adding to Nikolai's answer, which got the switch compiling but not working with transitions, here's a version of his example that does support transitions.

    struct RootView: View {
      @State var containedViewType: ContainedViewType = .home
    
      var body: some View {
         VStack {
           // custom header goes here
           containedView()
         }
      }
    
      func containedView() -> some View {
         switch containedViewType {
         case .home: return AnyView(HomeView()).id("HomeView")
         case .categories: return AnyView(CategoriesView()).id("CategoriesView")
         ... 
      }
    }
    

    Note the id(...) that has been added to each AnyView. This allows SwiftUI to identify the view within it's view hierarchy allowing it to apply the transition animations correctly.

提交回复
热议问题