使用 Toggle 为视图的 hiding/showing 设置动画

Animating the hiding/showing of a view with a Toggle

这是我的代码

@State private var show = false

...

Form {
    Toggle(isOn: $show, label: { Text("Show the text?") })
    if show {
        Text("Hello World")
    }
}

使用具有操作 self.show.toggle() 的按钮,我可以使用 withAnimation{} 声明,但我不确定如何使用切换来完成。

您可以像这样将 .animation(.easeOut) 修饰符添加到文本视图中 -

@State private var show = false

...

Form {
    Toggle(isOn: $show, label: { Text("Show the text?") })
    if show {
        Text("Hello World")
           .animation(.easeOut)
    }
}

通过添加此修饰符,应用到视图的任何更改都将被动画化。

来自 Apple's basic animation tutorial - 当您在视图上使用 animation(_:) 修饰符时,SwiftUI 会为视图的可动画属性的任何更改设置动画。视图的颜色、不透明度、旋转、大小和其他属性都是可动画的。

您还可以为视图的特定部分或您想要的显示方式设置动画,例如将颜色设置为黑色,不透明度为 0,如果 show == true 则设置回 1(完全可见) )

@State private var show = false

...

Form {
    Toggle(isOn: $show, label: { Text("Show the text?") })
    if show {
        Text("Hello World")
           .foregroundColor(show ? Color.black : Color.black.opacity(0)) // if show is true than foreground color is black, if show is false than color is black with opacity 0.0 (not visible)
           .animation(.easeOut)
    }
} 

这可以给你更好的动画:

  Form
  {
    
    Toggle(isOn: $show, label: { Text("Show the text?") })
    
    Group
    {
        if show { Text("Hello World") } else { EmptyView() }
    }
 }
   .animation(.easeOut)