Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

swiftui - Hosting Controller When Using iOS 14 @main

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 be running on iOS.

Previously in the SceneDelegate I’d have code that would say something like:

let contentView = ContentView()
window.rootViewController = UIHostingController(rootView: contentView)

Now I just have an @main file with:

var body: some Scene {
    WindowGroup {
        ContentView()
    }
}

So where does the Hosting Controller stuff go (or how else can I access UIKit features that SwiftUI doesn’t have? (Specifically, I want to mess with the status bar, auto hiding the home indicator, and a few things about light/dark mode that SwiftUI’s preferredColorScheme doesn’t cover.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) {
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...