Search code examples
iosswiftswiftuitransition

SwiftUI: How to add transitions between conditional views?


In my app I have such view:

import SwiftUI

let defaults = UserDefaults.standard

struct ContentView: View {
    @State var haveSeenIntroduction: Bool = defaults.bool(forKey: "haveSeenIntroduction")

    var body: some View {
        ZStack {
            if self.haveSeenIntroduction {
                DefaultView()
            } else {
                IntroductionView(haveSeenIntroduction: $haveSeenIntroduction)
            }
        }.transition(.scale)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In "IntroductionView" I have such button:

Button(action: {
    let generator = UINotificationFeedbackGenerator()
    generator.notificationOccurred(.success)

    let defaults = UserDefaults.standard

    defaults.set(true, forKey: "haveSeenIntroduction")

    withAnimation {
        self.haveSeenIntroduction = true
    }
})

When I press the button, when using ZStack in the parent view, transition looks buggy (previous view "jumps up" and it looks horrible), when using Group transition does not happen at all. How can I fix this behaviour and implement transition between these two views without lags, jumps, etc?


Solution

  • You should set .transition(.scale) on your views, not the stack to show the transition