SwiftUI animation is as simple as adding any other modifier in SwiftUI.
There are only two things required to perform animation
- a trigger: an event which can start the animation
- change: this can be a variable tied to a view’s property
Lets see an example of change in property without animation and then with animation:
Without Animation:
import SwiftUIstruct SwiftUIAnimationIntro: View {
@State private var flag = false
var body: some View {
VStack {
RoundedRectangle(cornerRadius: 20)
.foregroundColor(.orange)
.frame(width: 200, height: 200)
.offset(x: 0, y: flag ? 400 : 0)
Spacer()
Button("Animate") {
flag.toggle()
}
}
.font(.title)
}
}
When I said adding animation is as simple as adding a modifier, which is literally that. Let’s look at an example:
struct SwiftUIAnimationIntro: View {
@State private var flag = false
var body: some View {
VStack {
RoundedRectangle(cornerRadius: 20)
.foregroundColor(.orange)
.frame(width: 200, height: 200)
.offset(x: 0, y: flag ? 400 : 0)
Spacer()
Button("Animate") {
flag.toggle()
}
}
.animation(Animation.easeInOut, value: flag)
.font(.title)
}
}
As we can see, by adding a simple animation modifier, we get to animate the view.
With that we have reached the end of this article. Thank you once again for reading. Subscribe to our weekly newsletter at https://www.devtechie.com