簡體   English   中英

將值傳遞給另一個視圖:使用 State 並在 SwiftUI 中綁定

[英]Passing Value to a Another View: Using State and Binding In SwiftUI

我正在嘗試將我的 View LingView 中的值傳遞給另一個 View ContentView。 我在登錄視圖中有一個 state 變量,如下所示:

@State var userName: String = ""
  @State private var password: String = "" 

然后我在兩個地方傳遞來自 Content View Constructor 的值: 這是在 RootView

var body: some View {
      ContentView(userName: LoginView().$userName)
      .fullScreenCover(isPresented: $authenticator.needsAuthentication) {
        LoginView()
          .environmentObject(authenticator) // see note
      }
  }

這是在內容視圖中:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(userName: Login().$userName)
            .environmentObject(Authenticator())
    }
}

我想使用該變量傳遞給數據庫文件使用的 getPictures() function。 我有點困惑我應該做什么。 在這種情況下,父視圖是 LoginView 正確的嗎? 我不確定為什么我不斷收到:在 scope 中找不到類型“用戶名”。

@Binding var userName: String
    
    print(userName)
    
    
    var pictureURL = DbHelper().getPictures()

運行以下代碼后。 我知道您應該將 state 設為視圖私有,但在這種情況下,我如何將 state 值傳遞給內容視圖? LoginView 不直接調用 ContentView。 可能我不了解 Bindings 和 State,但我看過這篇文章: https://learnappmaking.com/binding-swiftui-how-to/

您正在初始化兩個單獨的登錄視圖。 因此,傳遞給ContentView的用戶名綁定與您在.fullscreenCover下的綁定不同

為了使它工作,你可以在RootView中聲明一個State變量,

@State private var userName: String = "" // In RootView

然后將其綁定傳遞給ContentViewLoginView

@Binding var userName: String // In ContentView and LoginView

簡單地說, State保存您的實際用戶名值,而Binding為您提供了一種從其他地方查看和更改它的方法。

暫無
暫無

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

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