SwiftUI - Ugly Animation switching from portrait to landscape

Viewed 162

I have this app for iPhone and I would like to have two views, one for portrait and one for landscape. So I have this on ContentView:

struct ContentView: View {
    var body: some View {          
      Group {
        GeometryReader { geometry in
          if (geometry.size.width > geometry.size.height) {
            ZStack {
              Color.red
                .edgesIgnoringSafeArea(.all)
              
              Text("LANDSCAPE")
                .font(.title)
                .foregroundColor(.white)
            }
          }
          
          if (geometry.size.width < geometry.size.height) {
            
            ZStack {
              Color.blue
                .edgesIgnoringSafeArea(.all)
              
              Text("PORTRAIT")
                .font(.title)
                .foregroundColor(.white)
            }
          }
        }
      }
      .background(Color.black.edgesIgnoringSafeArea(.all))
    }
}

When the iPhone rotates, I have this ugly animation:

enter image description here

I don't like the views coming from the edge and rotating like that. Any way to make like the view is in place and just change colors and text?

Any way to improve this and create something more beautiful?

1 Answers

Here is possible solution - just changed combination of used containers.

Tested with Xcode 12.1 / iOS 14.1

demo

struct ContentView: View {
    var body: some View {
        GeometryReader { gp in
            ZStack {
                LANDSCAPEView().opacity(gp.size.width > gp.size.height ? 1.0 : 0)
                PORTRAITView().opacity(gp.size.width < gp.size.height ? 1.0 : 0)
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .animation(.default)
        .background(Color.black.edgesIgnoringSafeArea(.all))
    }
}

struct LANDSCAPEView: View {
    var body: some View {
        Color.red
            .overlay(
                
                Text("LANDSCAPE")
                    .font(.title)
                    .foregroundColor(.white)
            )
            .edgesIgnoringSafeArea(.all)
    }
}

struct PORTRAITView: View {
    var body: some View {
        Color.blue.overlay(
            
            Text("PORTRAIT")
                .font(.title)
                .foregroundColor(.white)
        )
        .edgesIgnoringSafeArea(.all)
    }
}
Related