🔹 SwiftUI 动画
SwiftUI 提供声明式动画,核心就是 .animation
修饰符和 withAnimation
。
1. 隐式动画(Implicit Animation)
只要状态值发生变化,UI 会自动过渡。
struct ImplicitAnimationView: View {
@State private var isScaled = false
var body: some View {
VStack {
Circle()
.fill(Color.blue)
.frame(width: isScaled ? 200 : 100, height: isScaled ? 200 : 100)
.animation(.easeInOut(duration: 1), value: isScaled) // 隐式动画
Button("切换") {
isScaled.toggle()
}
}
}
}
2. 显式动画(Explicit Animation)
用 withAnimation { ... }
包裹状态变化。
struct ExplicitAnimationView: View {
@State private var isRotated = false
var body: some View {
VStack {
Rectangle()
.fill(Color.red)
.frame(width: 100, height: 100)
.rotationEffect(.degrees(isRotated ? 180 : 0))
Button("旋转") {
withAnimation(.spring(response: 0.5, dampingFraction: 0.4)) {
isRotated.toggle()
}
}
}
}
}
3. 过渡动画(Transition Animation)
针对视图的 插入和删除。
struct TransitionAnimationView: View {
@State private var showBox = false
var body: some View {
VStack {
if showBox {
Rectangle()
.fill(Color.green)
.frame(width: 150, height: 150)
.transition(.scale) // 进入/退出动画
}
Button("切换") {
withAnimation(.easeInOut) {
showBox.toggle()
}
}
}
}
}
4. 动画修饰器(Animation Modifier)
绑定到某个值,值变化时触发动画。
struct AnimationModifierView: View {
@State private var offsetX: CGFloat = 0
var body: some View {
Circle()
.frame(width: 80, height: 80)
.offset(x: offsetX)
.onTapGesture {
offsetX = offsetX == 0 ? 200 : 0
}
.animation(.easeInOut(duration: 1), value: offsetX) // 绑定值
}
}
🔹 UIKit 动画
在 UIKit 里,主要靠 UIView.animate 和 核心动画(Core Animation)。
1. UIView.animate
UIView.animate(withDuration: 0.5, animations: {
someView.alpha = 0.0
someView.frame.origin.y += 100
}) { finished in
print("动画完成")
}
2. 弹簧动画
UIView.animate(withDuration: 0.8,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 0.5,
options: [],
animations: {
someView.transform = CGAffineTransform(scaleX: 2, y: 2)
},
completion: nil)
3. 核心动画(CAAnimation)
适合更复杂的场景。
let animation = CABasicAnimation(keyPath: "position.x")
animation.fromValue = 0
animation.toValue = 200
animation.duration = 1.0
someView.layer.add(animation, forKey: "moveX")
总结
- SwiftUI → 用
.animation
、withAnimation
、transition
。 - UIKit → 用
UIView.animate
、UIViewPropertyAnimator
、CAAnimation
。