我想使用一个按钮来触发矩形上的动画,但我不知道如何从不是调用动画的对象调用动画。
var body: some View {
GeometryReader { fullView in
ScrollView() {
VStack{
Rectangle()
.foregroundColor(.white)
.frame(width: 150, height: 150)
Button(action: {
print("Here")
//Trigger animation here
}){
Text("Button")
}
Spacer()
}
}
}
}
}
这是我使用的通用代码。
答案 0 :(得分:0)
您可以只更改 withAnimation(_:_:)
块中的 @State
变量的值。
这是一个更简单的版本,有两个选项:
代码:
struct ContentView: View {
@State private var scale: CGFloat = 1
var body: some View {
VStack {
Rectangle()
.frame(width: 150 * scale, height: 150 * scale) // 1
// .frame(width: 150, height: 150) // 2
// .scaleEffect(scale) // 2
Button("Button") {
print("Here")
//Trigger animation here
withAnimation {
scale = 2.5 - scale
}
}
Spacer()
}
}
}
2.5
来自 1 + TARGET_SCALE
。 1 -> 1.5, 1.5 -> 1
。