[英]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{}
语句为幻灯片设置动画,但我不确定如何使用切换来实现。
这可以给你更好的动画:
Form
{
Toggle(isOn: $show, label: { Text("Show the text?") })
Group
{
if show { Text("Hello World") } else { EmptyView() }
}
}
.animation(.easeOut)
您可以像这样将.animation(.easeOut)
修饰符添加到您的文本视图中 -
@State private var show = false
...
Form {
Toggle(isOn: $show, label: { Text("Show the text?") })
if show {
Text("Hello World")
.animation(.easeOut)
}
}
通过添加此修改器,应用于视图的任何更改都将被动画化。
来自Apple 的基本动画教程-当您在视图上使用 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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.