How to smooth transition in a conditional view

Hi im doing an app for iPad an iPhone so I have a condition to detect the screen size .regular o .compact then I show an iPad navigation view or a tabview on iPhone or .compact view.
Code Block swift
                if self.sizeClass == .compact && settings.getShowHomeOnIphone()
                {
                    withAnimation(.easeInOut(duration: 1) ){
                        return NavigationViewForiPhone()
                    }
                    
                }
                else
                {
                    withAnimation(.easeInOut(duration: 1) ){
                        return NavigationViewForiPad()
                    }
                    
                }

so the problem is that when on the iPhone (plus size and max size) change to landscape or portrait the views changes is not smooth I try a lot of thing to animate the transition but I don't find the way.

Any idea or suggestion?

Replies

Can you show the code in action? I tried to reproduce and managed to get it working fine.

See if that works out for you:

Code Block swift
struct TestingView: View {
    @Environment(\.horizontalSizeClass) var sizeClass    
    var body: some View {
        if self.sizeClass == .compact {
            return AnyView(TabView {
                Text("Hello World!")
                    .tabItem {
                        Text("Hello")
                }
            })
        } else {
            return AnyView(NavigationView {
                List {
                    Text("Hi")
                }
                Text("Hello World!")
            })
        }
    }
}


Howdy!

First and foremost, please don't rely on AnyView when you can just use an if statement inside a @ViewBuilder property or method. For example, mwanis' answer could be written as:

Code Block
struct TestingView: View {
@Environment(\.horizontalSizeClass) var sizeClass
@ViewBuilder var body: some View {
if sizeClass == .compact {
TabView {
Text("Hello World!")
.tabItem {
Text("Hello")
                    }
}
} else {
NavigationView {
List {
Text("Hi")
}
Text("Hello World!")
}
}
}
}


You could customize how these two views transition with the .transition modifier, but I generally recommend instantly changing root-level navigation views when adjusting to size classes.

Also for reference, the Fruta sample code project also transitions between two root navigation views if you're interested to see how it's handled there.
https://developer.apple.com/documentation/swiftui/fruta_building_a_feature-rich_app_with_swiftui