这样的事情怎么样:
- 将观察到的对象作为主要对象(您的
enviornmentObject)。
- 向它添加
UIImage 属性或您想要在视图之间共享的任何属性(毕竟这是environmentObject 的工作
- 共享环境对象
这是你的课
class AppState: ObservableObject {
@Published var selectedImage: UIImage? = nil // default it to nil in case nothing is selected
}
这是你的主视图
struct ContentView: View {
@EnviornmentObject var appState: AppState
@State var presentModal: Bool = false
var body: some View {
VStack {
// Image can now easily be accessed by calling self.appState.selectedImage in any view that has @EnviornmentObject var appState: AppState
if(self.appState.selectedImage != nil) {
Image(uiImage: self.appState.selectedImage!)
} else {
// Image doesn't exist, add a placeholder
Text("No image selected")
}
Button("Show Modal") {
self.presentModal.toggle()
}
}.sheet(isPresented: self.$presentModal) {
ModalView(presentModal: self.$presentModal)
}
}
}
// 您的 ImagePicker 视图或任何其他将更改所选图像的视图
struct ModalView: View {
@EnviornmentObject var appState: AppState
@Binding var presentModal: Bool = false
var body: some View {
// Your logic to pick image goes here, I will simulate a button click
Button("I will set an image") {
self.appState.selectedImage = UIImage(named: "test.jpg")
self.presentModal.toggle()
}
}
}
在您的 SceneDelegate 中(非常重要)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView().environmentObject(AppState()) // <- The important part
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
您的模态视图(或您的图像选择器视图,实际上任何东西)
编辑:我同意它应该以模态形式呈现;但是,这不是 100% 必要的。不管是否将其呈现为模态,这都应该可行。