【问题标题】:Animating the hiding/showing of a view with a Toggle使用 Toggle 动画隐藏/显示视图
【发布时间】:2020-11-08 10:15:02
【问题描述】:
这是我的代码
@State private var show = false
...
Form {
Toggle(isOn: $show, label: { Text("Show the text?") })
if show {
Text("Hello World")
}
}
使用具有self.show.toggle() 操作的按钮,我可以使用
withAnimation{} 声明,但我不知道如何通过切换来实现。
【问题讨论】:
标签:
ios
swift
iphone
swiftui
【解决方案1】:
这可以给你更好的动画:
Form
{
Toggle(isOn: $show, label: { Text("Show the text?") })
Group
{
if show { Text("Hello World") } else { EmptyView() }
}
}
.animation(.easeOut)
【解决方案2】:
您可以像这样将.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 - 当您在视图上使用动画(_:) 修饰符时,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)
}
}