SwiftUI - 动画调整视图的框架大小

15

如何使视图的大小产生动画效果,使得视图可以使用框架高度增长或缩小?我需要在两个已知尺寸之间进行过渡。


你是怎么尝试的? - Asperi
2个回答

16

我不知道您确切需要什么,但这里有一个非常基本的例子,其中包含一个Rectangle,当您点击Button时,它会被缩放:

我不确定您需要的内容,但这里有一个非常基本的示例,其中包含一个Rectangle,当您点击Button时,它会被缩放:

struct ContentView: View {

    @State var animate = false

    var body: some View {
        VStack {
            Button(action: {
                withAnimation {
                    self.animate.toggle()
                }
            }, label: {
                Text("Animate")
            })
            Rectangle()
                .foregroundColor(.blue)
                .frame(width: self.animate ? 100 : 150, height: self.animate ? 60 : 90)
        }
    }
}
请在您的下一个问题中添加一些代码或编辑该问题,以便人们可以提供更具体的答案。

11
由于 withAnimation { } 会在闭包内部动画化与状态变化相关的所有内容,因此我们可以使用 .animation() 修饰符来动画化特定的内容。
struct ContentView: View {

    @State var animate = false

    var body: some View {
        VStack {
            Button(action: {
                    self.animate.toggle()
            }, label: {
                Text("Animate")
            })
            Rectangle()
                .foregroundColor(.blue)
                .frame(width: animate ? 100 : 150, height: animate ? 60 : 90)
                .animation(.default, value: animate) //you can change the animation you need 
            }
        }
    }

.animation(_ animation: Animation)修饰符已被弃用。正确使用该方法的方式是同时传递value参数。例如:.animation(.default, value: animate) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接