Blockchain ク gainst to the list
This article uses the current latest version of Xcode 12 + macOS Big sur + iOS14
SwiftUI, like UIKit, offers Explicit and Implicit animations.
Explicit animation
In UIKit explicit animations are triggered by UIView.animate, as follows
UIView.animate(withDuration: 0.5) {
someview.alpha = 0
}
Copy the code
In SwiftUI we use withAnimation for explicit animation, for example:
@State var alphaValue: Double = 1
var body: some View {
VStack {
Text("Hello, World!")
.opacity(self.alphaValue)
.padding()
Button("Start") {
withAnimation(.easeIn(duration: 0.5)) {
self.alphaValue = 0}}}}Copy the code
An implicit animation
Set the Modifier to the View’s animation decorator to provide animations that automatically add transitions when the view-related properties change. Such as
@State var isClicked: Bool = false
var body: some View {
VStack {
RoundedRectangle(cornerRadius: 25)
.foregroundColor(self.isClicked ? .red : .green)
.frame(width: self.isClicked ? CGFloat(300.0) : CGFloat(200.0), height: 200)
.padding()
.animation(.default)
Button("Start") {
self.isClicked.toggle()
}
}
}
Copy the code
The operation effect is as follows:
Animation structure
The Animation structure of the system provides some common animations for us, such as easeOut, easeIn, easeInOut spring and other common animations. Both explicit and implicit animations require an Animation by passing in a static member of the Animation directly,
RoundedRectangle(cornerRadius: 25)
.
.animation(Animation.easeOut)
Copy the code
You can also call the static method of the Animation to set parameters such as the Animation time of 1 second
RoundedRectangle(cornerRadius: 25)
.
.animation(Animation.easeOut(duration: 1))
Copy the code
Repetition of the animation
Animation Decorators with repeatForever repeatCount can be used to complete looper animations such as:
@State var isClicked: Bool = false
var body: some View {
VStack {
Image(systemName: "suit.heart.fill")
.resizable()
.scaledToFit()
.foregroundColor(.red)
.frame(width: 200, height: 200, alignment: .center)
.scaleEffect(self.isClicked ? 0.5: 1)
.animation(Animation.linear(duration: 0.5).repeatForever())
.padding()
Button("Start") {
self.isClicked.toggle()
}
.padding()
}
}
Copy the code
Results the following
Delay animation
Animation’s Delay decorator can delay the Animation startup time, which is useful for Animation combinations of multiple views, such as implementing individual loaded indicators:
@State var isClicked: Bool = false
var body: some View {
VStack {
HStack{
let scale: CGFloat = isClicked ? 0 : 1
ForEach(0 ..< 5){ index in
Circle()
.frame(width: 50, height: 50, alignment: .center)
.scaleEffect(scale)
.foregroundColor(.red)
.animation(Animation.linear(duration: 0.8).repeatForever().delay(0.2 * Double(index)))
}
}
Button("Start") {
self.isClicked.toggle()
}
.padding()
}
}
Copy the code
The effect is as follows: