Hosting Controller When Using iOS 14 @main

前端 未结 3 2003
醉酒成梦
醉酒成梦 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:15

    I was facing the same problem. I played around with an alternative solution with zero set up, meaning it would work with SwiftUI App and Playgrounds (I even wrote a set of Playgrounds for documentation) - The package is called SwiftUIWindowBinder.

    Example using WindowBinder... See docs for other usage, such as event view modifiers (like onTapGesture), or the convenience of WindowButton.

    import SwiftUI
    import SwiftUIWindowBinder
    
    struct ContentView : View {
        /// Host window state (will be bound)
        @State var window: Window?
    
        var body: some View {
            // Create a WindowBinder and bind it to the state property `window`
            WindowBinder(window: $window) {
              
                Text("Hello")
                    .padding()
                    .onTapGesture {
                        guard let window = window else {
                            return
                        }
    
                        print(window.description)
                    }
              
            }
        }
    }
    

    Only caveat of the package is you cannot use a host window to construct your view. I have a whole Playground page on this.

提交回复
热议问题