How to Make Animation with SwiftUI (Dice App)

HariAgusWidakdo
2 min readJul 1, 2024

--

Bismillah, create a rotating animation with SwiftUI that will be applied in the example dice application. For the design of the application is very simple, there is only 1 button and 2 image. Ok go ahead :

struct ContentView: View {

@State var leftDiceNumber = 1
@State var rightDiceNumber = 1

var body: some View {
VStack {
Spacer()

Button {
leftDiceNumber = Int.random(in: 1...6)
rightDiceNumber = Int.random(in: 1...6)
} label: {
Circle()
.frame(width: 120, height: 120)
.overlay {
Text("ROLL")
.foregroundColor(.white)
.font(.system(size: 24))
.bold()
}
}

Spacer()

HStack {
Image("dice\(leftDiceNumber)")
.resizable()
.frame(width: 140, height: 140)

Image("dice\(rightDiceNumber)")
.resizable()
.frame(width: 140, height: 140)

}
.offset(y: -200)
}
.padding()
}
}

Only needs the code as above fo the design display, now let’s try to make the animation

@State var isAnimating = false

We create a global variable using @State because the value will change later. Next we change the Button when clicked to be like this :

Button {
withAnimation(Animation.easeInOut(duration: 0.5)) {
isAnimating = true
}

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
leftDiceNumber = Int.random(in: 1...6)
rightDiceNumber = Int.random(in: 1...6)
isAnimating = false
}
}

The code above is used to wrap the status change so that the change is animated with a duration of 0.5 seconds. And finally, we will add animation to the 2 dice images

Image("dice\(leftDiceNumber)")
.resizable()
.frame(width: 140, height: 140)
.rotationEffect(.degrees(isAnimating ? 360 : 0))
.scaleEffect(isAnimating ? 1.2 : 1)

Image("dice\(rightDiceNumber)")
.resizable()
.frame(width: 140, height: 140)
.rotationEffect(.degrees(isAnimating ? 360 : 0))
.scaleEffect(isAnimating ? 1.2 : 1)

We use .rotationEffect() to rotate the view and .scaleEffect() to scale the view. And for the result will be like this

Thank you for reading my short article, hopefully this article can be useful 🌟🌟🌟

--

--

HariAgusWidakdo
HariAgusWidakdo

Written by HariAgusWidakdo

Mobile Developer | Kotlin | SwiftUI 📱. Sometimes write my story 📚

No responses yet