Kiran Jasvanee
Kiran Jasvanee

Reputation: 6554

Animate hide and show of T in SwiftUI

enter image description here enter image description here enter image description here

When I tap the Toggle Text, It must hide or show Favorites Text with fade animation and delay.
Or Give me some animations while Text going to be displayed on the screen. I tried a few Animation ways, but it's not working so far. Here is the code.

struct ContentView: View {

    @State var showText: Bool
    var body: some View {
        VStack() {
            Spacer()
            Image(systemName: "star.fill")

            if self.showText {
                // Changing selection value.
                    Text("Favorites")
                        .font(.custom("Helvetica Neue", size: 20))
                        .animation(Animation.easeOut(duration: 2.0).delay(0.5))
            }

            Spacer()
                .frame(height: 50)

            Button(action: {
                self.showText.toggle()
            }) {
                Text("Toggle Text")
            }
            Spacer()
        }
        .padding(5)
        .font(.custom("Helvetica Neue", size: 14))
    }
}

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

Upvotes: 1

Views: 2823

Answers (1)

Asperi
Asperi

Reputation: 257603

Here is possible approach (Tested & works with Xcode 11.2 / iOS 13.2)

Note: Preview is bad in processing transitions, so test either with Simulator or with real device.

struct ContentView: View {

    @State var showText: Bool = false
    var body: some View {
        VStack() {
            Spacer()
            Image(systemName: "star.fill")

            if self.showText {
                // Changing selection value.
                Text("Favorites")
                    .font(.custom("Helvetica Neue", size: 20))
                    .transition(.opacity)  // << transition works in add/remove view
            }

            Spacer()
                .frame(height: 50)

            Button(action: {
                withAnimation(Animation.easeOut(duration: 2.0).delay(0.5)) {
                    self.showText.toggle() // << transition requires explicit animation
                }
            }) {
                Text("Toggle Text")
            }
            Spacer()
        }
        .padding(5)
        .font(.custom("Helvetica Neue", size: 14))
    }
}

Upvotes: 1

Related Questions