Home > Software design >  Fading Text in with Duration in SwiftUI
Fading Text in with Duration in SwiftUI

Time:08-08

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)
    }

CodePudding user response:

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)
        }
    }
}

CodePudding user response:

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()
            }
        }
    }
  }
}
  • Related