swiftui - SwiftUI 没有隐藏动画
问题描述
我注意到,当我为背景着色时,删除视图时不会得到动画。
如果我删除Color(.orange).edgesIgnoringSafeArea(.all)
然后隐藏动画将起作用,否则Modal
会突然消失。有什么解决办法吗?
struct ContentView: View {
@State var show = false
func toggle() {
withAnimation {
show = true
}
}
var body: some View {
ZStack {
Color(.orange).edgesIgnoringSafeArea(.all)
Button(action: toggle) {
Text("Modal")
}
if show {
Modal(show: $show)
}
}
}
}
struct Modal: View {
@Binding var show: Bool
func toggle() {
withAnimation {
show = false
}
}
var body: some View {
ZStack {
Color(.systemGray4).edgesIgnoringSafeArea(.all)
Button(action: toggle) {
Text("Close")
}
}
}
}
解决方案
您需要制作可动画容器来保存已移除的视图(这使得将动画保存在一个地方成为可能)。这是可能的解决方案。
使用 Xcode 12 / iOS 14 测试
struct ContentView: View {
@State var show = false
func toggle() {
show = true // animation not requried
}
var body: some View {
ZStack {
Color(.orange).edgesIgnoringSafeArea(.all)
Button(action: toggle) {
Text("Modal")
}
VStack { // << major changes
if show {
Modal(show: $show)
}
}.animation(.default) // << !!
}
}
}
struct Modal: View {
@Binding var show: Bool
func toggle() {
show = false // animation not requried
}
var body: some View {
ZStack {
Color(.systemGray4).edgesIgnoringSafeArea(.all)
Button(action: toggle) {
Text("Close")
}
}
}
}
推荐阅读
- php - codeigniter 使用通配符(任意)路由固定字符串或字符
- java - 使用 Java 中的任务调度程序更新表时行被锁定
- prolog - 给定带有成员谓词的查询,回溯如何工作的混乱
- java - 如何在列表视图上添加对象?
- excel - Excel:如何计算单元格范围内的特定字符以用于单独范围内的不同类别
- python - Selenium WebDriver 将数据逐行写入CSV
- java - 引导类路径未与 -source 1.7 一起设置 - netbeans
- python - Matplotlib:子图中的不同 x 轴标签
- namespaces - 在命名空间 Kubernetes 中创建入口控制器
- mysql - 无法在 localhost 连接到 MySQL:3306 使用 root 用户