Search code examples
iosswiftswiftui

SwiftUI - Animation when hiding view


I am trying to figure out an animation with SwiftUI when showing or hiding a view in a group of a body in a view. I have this code:

    var body: some View {

        Group {

            if isIntroShown {
                EAIntroViewContentView()
                .transition(AnyTransition.opacity.animation(.easeInOut(duration: 1.0)))
            }

            if mainhomeMode == .mylists {
                MyLists()
                    .onReceive(publisher) { (payload) in
                        self.toggleMainView()
                    }
            } else {
                CarsHome()
                    .onReceive(publisher) { (payload) in
                        self.toggleMainView()
                    }
            }

        }.onReceive(publisherIntro) { (payload) in
            self.onShowIntroButton()
        }
    }

When hiding EAIntroView, the transition animation works properly, but the block pops moving up the mainhomeMode to the top of the window without animations. How can I hide and show the Intro view making the hide/show event smooth?


Solution

  • Well, after some tests and the reply of @Boris I have figured out what I need to do.

    The code should be like this:

        func onShowIntroButton() {
            withAnimation(.easeInOut(duration: 0.5)) {
                 isIntroShown.toggle()
            }
        }
    
        var body: some View {
    
                VStack{                    
                    if isIntroShown {
                        EAIntroViewContentView()
                        .transition(AnyTransition.opacity.animation(.linear(duration: 0.5)))
                    }
    
                    Spacer()
    
                    if mainhomeMode == .mylists {
                        MyLists()
                            .onReceive(publisher) { (payload) in
                                self.toggleMainView()
                            }
    
                    } else {
                        CarsHome()
                            .onReceive(publisher) { (payload) in
                                self.toggleMainView()
                            }
                    }
    
            }.onReceive(publisherIntro) { (payload) in
                self.onShowIntroButton()
            }
        }
    

    I am toggling views with notifications. So the animation must be called from the toggle() function.

    In this case I have to call the animation when the Intro view is toggled in the function onShowIntroButton().

    The VStak and the Spacer() also made the animation smoother.Hope it helps to other devs.