【问题标题】:How to change State variables one after another in SwiftUI?如何在 SwiftUI 中一个接一个地更改 State 变量?
【发布时间】:2022-12-17 07:24:30
【问题描述】:

我有一个带有几个按钮的Menu。每个按钮,代表一个 URL。 选择其中一个按钮后,我想显示一个 webView 使用 .fullScreenCover(isPresented:) 加载所述 URL

 @State private var showWebPage = false
    
 @State private var urlToLoad = ""

...

View()
     .toolbar {
         ToolbarItem(placement: .navigationBarTrailing) {
                                                       Menu {
                                                          Button("FAQ", action: {
                                        presentWebView(for: "https://example.com/faqsLink")
                                    })
                                                          Button("Privacy Policy", action: {
                                        presentWebView(for: "https://example.com/privacyLink")
                                    })
                                                          Button("Terms and Conditions", action: {
                                        presentWebView(for: "https://example.com/termsLink")
                                    })
}
}
}
.fullScreenCover(isPresented: $showWebPage) {
                    WebView(url: URL(string: urlToLoad)!)
                }

private func presentWebView(for url: String) {
   urlToLoad = url
   showWebPage.toggle()
}

每次我尝试这个时,当我切换showWebPage时,urlToLoad仍然是空的 我觉得这与 @State 的工作方式有关,但无法弄清楚,我还是 SwiftUI 的新手。

【问题讨论】:

    标签: swift swiftui swiftui-state swiftui-menu


    【解决方案1】:

    要在 SwiftUI 中一个接一个地更改状态变量,您可以在 showWebPage 变量的 Binding 上使用 onChange 修饰符。

      @State private var showWebPage = false
      @State private var urlToLoad = ""
    
      var body: some View {
        View()
          .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
              Menu {
                Button("FAQ", action: {
                  presentWebView(for: "https://example.com/faqsLink")
                })
                Button("Privacy Policy", action: {
                  presentWebView(for: "https://example.com/privacyLink")
                })
                Button("Terms and Conditions", action: {
                  presentWebView(for: "https://example.com/termsLink")
                })
              }
            }
          }
          .fullScreenCover(isPresented: $showWebPage, onChange: {
            if !$0 {
              urlToLoad = ""
            }
          }) {
            WebView(url: URL(string: urlToLoad)!)
          }
      }
    
      private func presentWebView(for url: String) {
        urlToLoad = url
        showWebPage.toggle()
      }
    

    【讨论】:

    • 谢谢你这么快,像 isPresented 之后那样的 onChange 给出了“调用中的额外参数‘onChange’”错误。你能再看看吗?
    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2019-11-10
    • 2020-04-10
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多