简体   繁体   中英

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?

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.

Have you tried anything like this?

withAnimation {
    self.toggleMainView()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM