SwiftUI - 如何从其他视图触发动画

时间:2021-05-08 14:58:38

标签: swiftui

我想使用一个按钮来触发矩形上的动画,但我不知道如何从不是调用动画的对象调用动画。

    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()
                    
                }
                
            }
            
        }
    }
}

这是我使用的通用代码。

1 个答案:

答案 0 :(得分:0)

您可以只更改 withAnimation(_:_:) 块中的 @State 变量的值。

这是一个更简单的版本,有两个选项:

  1. 缩放和更改布局
  2. 缩放而不改变布局

代码:

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_SCALE1 -> 1.5, 1.5 -> 1