Search code examples
swiftswiftui

Repeating Action Continuously In SwiftUI


How can I make an element such as a text field scale up and then down continuously?

I have this:

struct ContentView : View {
    @State var size:Double = 0.5

    var body: some View { 
        ZStack {
            Text("Hello!")
                 .padding()
                 .scaleEffect(size)
        }
    }
}

I know I need to increase size and then decrease it in some sort of loop but the following cannot be done in SwiftUI:

while true {

  self.size += 0.8
  sleep(0.2)
  self.size -= 0.8

}

Solution

  • Animation.basic is deprecated. Basic animations are now named after their curve types: like linear, etc:

    var foreverAnimation: Animation {
            Animation.linear(duration: 0.3)
            .repeatForever()
     }
    

    Source: https://forums.swift.org/t/swiftui-animation-basic-duration-curve-deprecated/27076