Search code examples
animationswiftuitransition

Different hide transition than show transition for a view


I get a different type of transition when hiding a view than when showing a view, even though the transition should be similar (ie if shown with slide in, the view should hide with a slide out). The example shows a .slide transition. When showing the view it slides in. But when I hide the view it disappears immediately, it doesn't slide out. Is this a bug or I'm doing something wrong? Using Xcode 11.4.1

    @State var isPanelVisible = false

    var body : some View {
        ZStack {
            Color.gray
            VStack {
                Button(action: {
                    withAnimation {
                        self.isPanelVisible = true
                    }
                }) {
                    Text("SHOW")
                }
            }

            if isPanelVisible {
                VStack {
                    Button(action: {
                        withAnimation {
                            self.isPanelVisible = false
                        }
                    }) {
                        Text("HIDE")
                    }
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.white)
                .transition(.slide)
            }
        }
    }

Solution

  • Here is fix

    if isPanelVisible {
        VStack {
            Button(action: {
                withAnimation {
                    self.isPanelVisible = false
                }
            }) {
                Text("HIDE")
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.white)
        .zIndex(1)                   // << here !!
        .transition(.slide)
    }