1

I would like to add animation so that when I click a button, the text inside my TextEditor (in iOS 14) fades out slowly (let's say with a duration of 1.5).

This is the code I am working with, but cannot get the text to fade out. Any ideas of what I am doing wrong?

struct FadeTextFromTextEditor: View {
   @State private var isAnimationOn = true
   @State private var text: String = ""
   @State private var resetText = true

    var body: some View {
        VStack(alignment: .center) {
             if #available(iOS 14.0, *)
             {
                  TextEditor(text: $text)
                  .border(Color.black, width: 1)
                  .padding(.horizontal, 5)
                  .padding(.vertical, 5)
                  .animation(.easeOut(duration: 1.5), value: resetText)
             }
            Button(action : {
                // If bool for fading the text out is set to true, use animation on the text
                if (self.isAnimationOn) {
                    withAnimation(.easeOut(duration: 1.5))
                    {
                        self.resetText.toggle()
                    }
                }
            })
            {
                Text("Animate")
                    .font(.headline)
                    .frame(width:125, height: 30)
                    .padding()
            }
        }
    }
}

Also, I did try taking out the withAnimation function call inside the Button's action as shown here, but that did not fix it.

        if (!self.isAnimationOn) {
             self.showMessageText.toggle()
        }
Sharanjit
  • 11
  • 1

1 Answers1

0

Not sure I've understood your expectation correctly, but you can get fade out by applying .opacity modifier, like below

TextEditor(text: $text).opacity(resetText ? 1 : 0)    // << here !!
  .border(Color.black, width: 1)
  .padding(.horizontal, 5)
  .padding(.vertical, 5)
  .animation(.easeOut(duration: 1.5), value: resetText)

Note: you don't need two animations (explicit and implicit) - they do the same in your case, so you can keep any one of them.

Asperi
  • 228,894
  • 20
  • 464
  • 690