SwiftUI 动画通常由状态驱动,这很好,但有时你真的想触发一个临时(通常是可逆的)动画来响应某些事件。例如,我想在点击按钮时暂时增加按钮的大小(释放按钮时,大小的增加和减少都应该作为单个动画发生),但我无法弄清楚这一点.
我认为它可以与过渡一起被破解,但不是很好。另外,如果我制作一个使用自动反转的动画,它会增加大小,减少它,然后跳回到增加的状态。
您可以使用@State与 longPressAction() 绑定的变量:
Beta 5 更新的代码:
struct ContentView: View {
var body: some View {
HStack {
Spacer()
MyButton(label: "Button 1")
Spacer()
MyButton(label: "Button 2")
Spacer()
MyButton(label: "Button 3")
Spacer()
}
}
}
struct MyButton: View {
let label: String
@State private var pressed = false
var body: some View {
return Text(label)
.font(.title)
.foregroundColor(.white)
.padding(10)
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(.green))
.scaleEffect(self.pressed ? 1.2 : 1.0)
.onLongPressGesture(minimumDuration: .infinity, maximumDistance: .infinity, pressing: { pressing in
withAnimation(.easeInOut(duration: 0.2)) {
self.pressed = pressing
}
}, perform: { })
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3257 次 |
| 最近记录: |