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



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

显示webView加载所述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()
}

每次我尝试这个,urlToLoad仍然是空的,当我切换showWebPage我觉得这与@State的工作方式有关,但不能弄清楚,我对SwiftUI还是很陌生。

在Delano的提示下,我设法想出了这个:

.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

的值希望这能帮助到一些人,我花在这上面的时间比我想象的一个菜单需要的时间要多。

最新更新