Search code examples
swiftuiswiftui-animation

Why the text appear at loading with animation?


I want to hide some text behind the NavigationBarTitle and show it when user press a button, it's working fine. The only problem is with the animation. At loading we see the text moving behind the NavigationBarTitle and that's not what i want.

How can i fix this?

I tried with offset and position but it's not working...

Code :

import SwiftUI

struct TestZStackNavigationView: View {
    @State var isShowed = false
    let screenSize: CGRect = UIScreen.main.bounds
    
    var body: some View {
        NavigationView {
            VStack(alignment: .center, spacing: 0){
                Text("Im the hidden text")
                    .fontWeight(.bold)
                    .foregroundColor(Color.white)
                    .frame(width: screenSize.width, height: 40, alignment: .center)
                    .background(Color.red)
//                    .offset(y: self.isShowed ? -315 : -355)
                    .position(x: screenSize.width / 2, y: self.isShowed ? 20 : -40)
                    .animation(.easeIn(duration: 0.5))

                Button(action: {
                    self.isShowed.toggle()
                }) {
                    Text("click me")
                }
                .navigationBarTitle(Text("Navigation Bar Title"), displayMode:.inline)
            }
        }
    }
}

struct TestZStackNavigationView_Previews: PreviewProvider {
    static var previews: some View {
        TestZStackNavigationView()
    }
}

Solution

  • There are two possibilities

    1. make animation per-state (and no other changes)
        .animation(.easeIn(duration: 0.5), value: isShowed)
    
    1. replace implicit animation as modifier and add explicit animation in action
            .position(x: screenSize.width / 2, y: self.isShowed ? 20 : -40)
        //    .animation(.easeIn(duration: 0.5)) // remove from here
    
        Button(action: {
          withAnimation(Animation.easeIn(duration: 0.5)) {   // << add this
            self.isShowed.toggle()
          }
        }) {
            Text("click me")
        }