如何在SwiftUI中一个接一个地更改状态变量?

How to change State variables one after another in SwiftUI?

提问人:Mihai Fischer 提问时间:12/16/2022 更新时间:12/16/2022 访问量:97

问:

我有一个有几个按钮。每个按钮代表一个 URL。 在选择其中一个按钮时,我想显示一个 webView,使用Menu.fullScreenCover(isPresented:)

 @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()
}

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

swift swiftui 状态 swiftui 菜单

评论


答:

0赞 Mihai Fischer 12/16/2022 #1

在德拉诺的提示下,我设法想出了这个:

 .fullScreenCover(isPresented: $showWebPage) {
                    WebView(url: URL(string: urlToLoad)!)
                        .withCloseButton(and: "FAQ")
                }
                .onChange(of: urlToLoad) { value in
                    log.info (value)
                    if !value.isEmpty {
                        showWebPage.toggle()
                    }
                }

在按钮操作中,我只是更新urlToLoad

希望这对某人有所帮助,我花在这上面的时间比我想象的菜单需要的要多。