簡體   English   中英

如何從 SwiftUI 中的減去子視圖中關閉視圖

[英]How it is possible to dismiss a view from a subtracted subview in SwiftUI

每當我的代碼變得太大時,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()
        })
        
    }

另一方面,我們有一個提取到子視圖的按鈕,以關閉模式和 go 回到原始視圖:

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")
        }
    }
}

這種情況最簡單的解決方案是使用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 測試

給 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 演示文稿,如工作表和警報。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM