SwiftUI 没有隐藏动画

Posted

技术标签:

【中文标题】SwiftUI 没有隐藏动画【英文标题】:SwiftUI no hide animation 【发布时间】:2020-10-05 13:24:50 【问题描述】:

我注意到,当我为背景着色时,删除视图时不会得到动画。

如果我删除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")
            
        
    

【问题讨论】:

【参考方案1】:

您需要制作可动画容器来保存已移除的视图(这使得将动画保存在一个地方成为可能)。这是可能的解决方案。

使用 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")
            
        
    

【讨论】:

以上是关于SwiftUI 没有隐藏动画的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI:输入字段键盘动画导致选项卡视图中的其他视图动画

按钮上的 SwiftUI 动画图像

SwiftUI 如何使圆形动画双向工作

一行代码为特定状态绑定SwiftUI视图动画

一行代码为特定状态绑定SwiftUI视图动画

SwiftUI:将动画添加到 Picker 而不将其添加到值中