ios - SwiftUI 与rotation3DEffect 动画冲突
问题描述
当我更改状态 HorizontalAlignment 并在 VStack(alignment: HorizontalAlignment) 中使用它时,内容将从左移动到中心。
我想通过点击按钮在中心和前导之间切换
当前效果:
预期效果:
import SwiftUI
struct ContentView: View {
@State private var rotateIn3D = false
@State private var horizontalAlignment: HorizontalAlignment = .leading
let weatherBg = LinearGradient(gradient: Gradient(colors: [Color.blue, Color.white]), startPoint: .topLeading, endPoint: .bottomTrailing)
var body: some View {
VStack{
ZStack { // Weather
VStack(alignment: horizontalAlignment) {
Text("Wednesday")
Text("18°")
.font(.system(size: 44))
.fontWeight(.thin)
Spacer()
Image(systemName: "cloud.sun.fill")
Text("Partly Cloudy")
.frame(width: 150, height: 20, alignment: .leading)
Text("H:21° L:12°")
}
.padding()
.background(Color.blue)
.background(Color.yellow)
.cornerRadius(22)
.foregroundColor(.white)
}.frame(width: 170, height: 170, alignment: .leading)
.rotation3DEffect(.degrees(rotateIn3D ? 12 : -12), axis: (x: rotateIn3D ? 90 : -45, y: rotateIn3D ? -45 : -90, z: 0))
.animation(Animation.easeInOut(duration: 2).repeatForever(autoreverses: true))
.onAppear() {
rotateIn3D.toggle()
}
Button(action: {
horizontalAlignment = .center
}, label: {
Text("Change Horizontal Alignment to center")
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.preferredColorScheme(/*@START_MENU_TOKEN@*/.dark/*@END_MENU_TOKEN@*/)
}
}
解决方案
只需将每个状态的每个值的动画分开即可。
使用 Xcode 12.1 / iOS 14.1 测试
// ... other code
.rotation3DEffect(.degrees(rotateIn3D ? 12 : -12), axis: (x: rotateIn3D ? 90 : -45, y: rotateIn3D ? -45 : -90, z: 0))
.animation(Animation.easeInOut(duration: 2).repeatForever(autoreverses: true),
value: rotateIn3D) // << here !!
.animation(.default, value: horizontalAlignment) // << here !!
.onAppear() {
rotateIn3D.toggle()
}
推荐阅读
- java - 将它们相乘后如何在数组中添加每个索引
- r - 如何使用矩阵乘法将原点从 (0,0) 转换为 (x,y)?
- c++ - 如何通过local_iterator擦除boost unordered_map中的元素?
- database - 如何与位于不同网络和国家的用户共享数据库
- scala - Scala中二叉树的尾递归最大深度方法
- c++ - 断开连接后正确杀死 asio stable_timer
- c# - 在实体框架中获取多对一对象的原始 SQL 脚本
- python - 当数据始终按特定顺序但具有不同值时,如何在 CSV 文件中查找特定值
- ms-access - 在拆分函数中跳过双逗号
- linux - 使用OpenGL修改操作系统在屏幕上显示的图像?