The animation is a powerful tool that allows you to make beautiful apps and it’s really easy to make infinity animation in SwiftUI that can make your app better.
Let’s create a Rectangle that you’ll be animating and State property width that keeps the width of this rectangle.
@State private var width: CGFloat = 100
var body: some View {
Rectangle()
.frame(width: width, height: 100)
}
Next, add onAppear to Rectangle that runs code when the view shows on the screen. Inside, there is needed withAnimation closure that changes width.
.onAppear(perform: {
withAnimation {
width = 10
}
})
When you run code, you’ll see that Rectangle has 10 as width but there isn’t any animation because it runs only once and it finishes. To make it infinity add Animation.easeIn.repeatForever() after withAnimation.
withAnimation(Animation.easeIn.repeatForever()) {
width = 10
}
Now, rectangle bounds all the time.
Now to make a better effect you can change the foreground color.
@State private var width: CGFloat = 100
@State private var color = Color.red
var body: some View {
Rectangle()
.frame(width: width, height: 100)
.foregroundColor(color)
.onAppear(perform: {
withAnimation(Animation.easeIn.repeatForever()) {
width = 10
color = .blue
}
})
}