【问题标题】:How it is possible to dismiss a view from a subtracted subview in SwiftUI如何在 SwiftUI 中从减去的子视图中关闭视图
【发布时间】:2020-12-11 16:56:06
【问题描述】:

每当我的代码变得太大时,SwiftUI 就会开始表现得很奇怪并产生错误:

"The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions"

所以我开始将我的代码分解为Extracted Subviews,我遇到的问题之一是如何从减去的子视图中消除视图。

例子:我们这里有LoginContentView这个视图包含一个按钮,当点击按钮时它会显示下一个视图UsersOnlineView

struct LoginContentView: View {
    
    @State var showUsersOnlineView = false
    
    var body: some View {
        
        Button(action: {
            self.showUsersOnlineView = true
        }) {
            Text("Show the next view")
        }
        .fullScreenCover(isPresented: $showUsersOnlineView, content: {
            UsersOnlineView()
        })
        
    }

另一方面,我们有一个提取到子视图的按钮,用于关闭模式并返回原始视图:

import SwiftUI

struct UsersOnlineView: View {
    var body: some View {
        
        ZStack {
            VStack {
                
                CloseViewButton()
                
            }
            
        }
        
    }
}

struct CloseViewButton: View {
    
    var body: some View {
        Button(action: {
            // Close the Modal
        }) {
            Text("Close the view")
        }
    }
}

【问题讨论】:

    标签: ios swift xcode swiftui


    【解决方案1】:

    给 sbview 定义视图是否显示的 state 属性。

    struct CloseViewButton: View {
    @Binding var showView: Bool
    
    var body: some View {
        Button(
             ShowView = false
        }) {
            Text("Close the view")
        }
    }
    

    }

    当你使用子视图时,给它属性

    CloseButtonView(showView: $showOnlineView)
    

    要允许子视图更改 isShown 属性,它需要获得一个绑定。

    关于演示模式。我认为这仅适用于 Swiftui 演示文稿,例如 sheet 和 alert。

    【讨论】:

      【解决方案2】:

      此场景最简单的解决方案是使用presentationMode 环境变量:

      struct CloseViewButton: View {
          @Environment(\.presentationMode) var presentationMode
          var body: some View {
              Button(action: {
                  presentationMode.wrappedValue.dismiss()
              }) {
                  Text("Close the view")
              }
          }
      }
      

      使用 Xcode 12.1 / iOS 14.1 测试

      【讨论】:

      • 我在我的项目上试过了,它对我不起作用,我的项目当你单击关闭按钮时,它会显示一个弹出窗口,是/否,当我将代码环境设置为是时它没有关闭模态,那么还有其他解决方案吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 2021-09-17
      • 2020-07-06
      相关资源
      最近更新 更多