0

I have been using the following UIView extension for quite a while to fade text in and out. I have been trying to figure out how to implement this with SwiftUI but so far haven't found anything that exactly addresses this for me. Any help would be greatly appreciated.

extension UIView {

   func fadeKey() {
      // Move our fade out code from earlier
      UIView.animate(withDuration: 3.0, delay: 2.0, options: UIView.AnimationOptions.curveEaseIn, animations: {
          self.alpha = 1.0 // Instead of a specific instance of, say, birdTypeLabel, we simply set [thisInstance] (ie, self)'s alpha
          }, completion: nil)
   }

    func fadeIn1() {
        // Move our fade out code from earlier
      UIView.animate(withDuration: 1.5, delay: 0.5, options: UIView.AnimationOptions.curveEaseIn, animations: {
            self.alpha = 1.0 // Instead of a specific instance of, say, birdTypeLabel, we simply set [thisInstance] (ie, self)'s alpha
            }, completion: nil)
    }
1

2 Answers 2

1

I assume this is what you wanted. Try this below code:

struct FadeView: View {
  @State var isClicked = false
  @State var text = "Faded Text"
  var body: some View {
    VStack {
        Text(text) //fade in and fade out
            .opacity(isClicked ? 0 : 1)
        Button("Click to animate") {
            withAnimation {
                isClicked.toggle()
            }
        }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could use withAnimation function and manipulate the duration, options and delay

struct ContentView: View {
    @State var isActive = false

    var body: some View {
        VStack {
            Button("Fade") {
                withAnimation(.easeIn(duration: 3.0).delay(2)){
                    isActive.toggle()
                }
            }
            
            Rectangle()
                .frame(width: 222.0, height: 222.0)
                .opacity(isActive ? 0 : 1)
        }
    }
}

2 Comments

That's a button I am trying to do this with text. The old code was used on a Label with the text.
if you want to animate a text just change the Rectangle with text

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.