Satoshi Nakajima
Satoshi Nakajima

Reputation: 2153

Fade-in/out animation with a boolean flag

I am trying to implement a simple "tap to toggle the visibility of the UI" in SwiftUI with fade in/out animation. The following code animates the fade-in effect of the Text element as I expected, but it immediately hides the Text element when isVisible become false.

I'd like to understand why this code does not work, and how to fix it in the most natural way.

import SwiftUI

struct ContentView: View {
    @State var isVisible = true
    var body: some View {
        ZStack {
            Rectangle()
                .foregroundColor(.blue)
                .gesture(TapGesture(count: 1).onEnded {
                    withAnimation(.easeInOut(duration: 1.0)) {
                        isVisible.toggle()
                    }
                })
            if isVisible {
                Text("Tap me!")
            }
        }
    }
}

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

I'm using Xcode 12.5 on Big Sur, and my iPhone is running iOS 14.5.1.

Upvotes: 3

Views: 9470

Answers (1)

Satoshi Nakajima
Satoshi Nakajima

Reputation: 2153

Thanks to Erik Philips, here is the answer.

import SwiftUI

struct ContentView: View {
    @State var isVisible = true
    var body: some View {
        ZStack {
            Rectangle()
                .zIndex(1)
                .foregroundColor(.blue)
                .gesture(TapGesture(count: 1).onEnded {
                    withAnimation(.easeInOut(duration: 1.0)) {
                        isVisible.toggle()
                    }
                })
            if isVisible {
                Text("Tap me!")
                    .zIndex(2)
            }
        }
    }
}

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

Upvotes: 6

Related Questions