Hosting Controller When Using iOS 14 @main

前端 未结 3 1998
醉酒成梦
醉酒成梦 2020-12-10 21:22

I’m experimenting with a “pure” SwiftUI app. It doesn’t have a SceneDelegate so I’m unsure of where to put Hosting Controller stuff that I need for when it’ll b

3条回答
  •  遥遥无期
    2020-12-10 22:06

    Here is a possible approach (tested with Xcode 12 / iOS 14)... but if you intend to use UIKit features heavily it is better to use UIKit Life-Cycle, as it gives more flexibility to configure UIKit part.

    struct ContentView: View {
    
        var body: some View {
          Text("Demo Root Controller access")
            .withHostingWindow { window in
                if let controller = window?.rootViewController {
                    // .. do something with root view controller
                }
            }
        }
    }
    
    extension View {
        func withHostingWindow(_ callback: @escaping (UIWindow?) -> Void) -> some View {
            self.background(HostingWindowFinder(callback: callback))
        }
    }
    
    struct HostingWindowFinder: UIViewRepresentable {
        var callback: (UIWindow?) -> ()
    
        func makeUIView(context: Context) -> UIView {
            let view = UIView()
            DispatchQueue.main.async { [weak view] in
                self.callback(view?.window)
            }
            return view
        }
    
        func updateUIView(_ uiView: UIView, context: Context) {
        }
    }
    

提交回复
热议问题