[英]How to update SwiftUI view after @AppStorage in a separate struct gets updated
[英]How to separate a dismiss button from the main struct of a swiftui view (that is presented by a uihostingviewcontroller) to its own struct?
我正在展示和關閉一個帶有按鈕的 swiftUI 視圖,它工作正常。
swiftUI 視圖:
struct SmartG_SwiftUI: View {
var dismissAction: (() -> Void)
var body: some View {
Button(action: {
dismissAction()
}) {}
}
}
我正在展示來自 UIKit 的 SwiftUI 視圖 controller,這樣:
let hostingVC = UIHostingVC(rootView: SmartG_SwiftUI(dismissAction: {
vc?.dismiss( animated: true, completion: nil )
}))
vc?.present(hostingVC, animated: true, completion: nil)
我的問題是,我怎么能把這個按鈕放在一個單獨的結構中? 所以為了有類似的東西:
struct SmartG_SwiftUI: View {
var dismissAction: (() -> Void)
Header()
}
struct Header: View {
Button(action: {
dismissAction() //unknown here
}) {}
}
SwiftUI 沒有手動滾動您自己的解除操作並將其傳入,而是通過環境變量提供了自己的解除操作。 我還沒有在托管 controller 基礎上使用它,但相反沒有看到任何跡象表明它不起作用...... (編輯:已經仔細檢查並且絕對適用於包裝在UIHostingController
中並呈現的 SwiftUI 視圖通過UIViewController.present(_:animation:completion:)
.)
一般的做法是:
struct MyView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
Button {
dismiss()
} label: {
Text("Close")
}
}
}
但這不一定是您托管 controller 中的最頂層視圖; 因為解除操作在環境中,它也將在您的Header
視圖中可用。
請注意,對於 iOS 13 或 14,語法有點冗長:
struct MyView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
Button {
presentationMode.wrappedValue.dismiss()
} label: {
Text("Close")
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.