Arturo Reyes
Arturo Reyes

Reputation: 309

Open a new window in Mac Catalyst

I am porting an iPad app using Mac Catalyst. I am trying to open a View Controller in a new window.

If I were using strictly AppKit I could do something as described in this post. However, since I am using UIKit, there is no showWindow() method available.

This article states that this is possible by adding AppKit in a new bundle in the project (which I did), however it doesn't explain the specifics on how to actually present the new window. It reads...

Another thing you cannot quite do is spawn a new NSWindow with a UIKit view hierarchy. However, your UIKit code has the ability to spawn a new window scene, and your AppKit code has the ability to take the resulting NSWindow it's presented in and hijack it to do whatever you want with it, so in that sense you could spawn UIKit windows for auxiliary palettes and all kinds of other features.

Anyone know how to implement what is explained in this article?

TL;DR: How do I open a UIViewController as a new separate NSWindow with Mac Catalyst?

Upvotes: 14

Views: 5996

Answers (2)

Lupurus
Lupurus

Reputation: 4189

With SwiftUI you can do it like this (thanks to Ron Sebro):

1. Activate multiple window support:

2. Request a new Scene:

struct ContentView: View {
    var body: some View {
        VStack {
            // Open window type 1
            Button(action: {
                UIApplication.shared.requestSceneSessionActivation(nil,
                                                                   userActivity: NSUserActivity(activityType: "window1"),
                                                                   options: nil,
                                                                   errorHandler: nil)
            }) {
                Text("Open new window - Type 1")
            }

            // Open window type 2
            Button(action: {
                UIApplication.shared.requestSceneSessionActivation(nil,
                                                                   userActivity: NSUserActivity(activityType: "window2"),
                                                                   options: nil,
                                                                   errorHandler: nil)
            }) {
                Text("Open new window - Type 2")
            }
        }
    }
}

3. Create your new window views:

struct Window1: View {
    var body: some View {
        Text("Window1")
    }
}
struct Window2: View {
    var body: some View {
        Text("Window2")
    }
}

4. Change SceneDelegate.swift:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)

            if connectionOptions.userActivities.first?.activityType == "window1" {
                window.rootViewController = UIHostingController(rootView: Window1())
            } else if connectionOptions.userActivities.first?.activityType == "window2" {
                window.rootViewController = UIHostingController(rootView: Window2())
            } else {
                window.rootViewController = UIHostingController(rootView: ContentView())
            }

            self.window = window
            window.makeKeyAndVisible()
        }
    }

Upvotes: 9

Ron Srebro
Ron Srebro

Reputation: 6862

EDIT : ADDED INFO ON HOW TO HAVE ADDITIONAL DIFFERENT WINDOWS LIKE PANELS

In order to support multiple windows on the mac, all you need to do is to follow supporting multiple windows on the iPad.

You can find all the information you need in this WWDC session starting minute 22:28, but to sum it up what you need to do is to support the new Scene lifecycle model.

Start by editing your target and checking the support multiple window checkmark

enter image description here

Once you do that, click the configure option which should take you to your info.plist. Make sure you have the proper entry for Application Scene Manifest

enter image description here

Create a new swift file called SceneDelegate.swift and just paste into it the following boilerplate code

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    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.
       guard let _ = (scene as? UIWindowScene) else { return }
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }


}

And you're basically done. Run your app, and hit command + N to create as many new windows as you want.

If you want to create a new window in code you can use this:

@IBAction func newWindow(_ sender: Any) {            
    UIApplication.shared.requestSceneSessionActivation(nil, userActivity: nil, options: nil) { (error) in
        //
    }
}

And now we get to the big mystery of how to create additional windows

The key to this is to create multiple scene types in the app. You can do it in info.plist which I couldn't get to work properly or in the AppDelegate.

Lets change the function to create a new window to:

@IBAction func newWindow(_ sender: Any) {     
    var activity = NSUserActivity(activityType: "panel")
    UIApplication.shared.requestSceneSessionActivation(nil, userActivity: activity, options: nil) { (error) in

    }
}

Create a new storyboard for your new scene, create at least one viewcontroller and make sure to set in as the initalviewcontroller in the storyboard.

Lets add to the appdelegate the following function:

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { 
        if options.userActivities.first?.activityType == "panel" {
            let configuration = UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
            configuration.delegateClass = CustomSceneDelegate.self
            configuration.storyboard = UIStoryboard(name: "CustomScene", bundle: Bundle.main)
            return configuration
        } else {
            let configuration = UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
            configuration.delegateClass = SceneDelegate.self
            configuration.storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
            return configuration
        }
    }

By setting the userActivity when requesting a scene we can know which scene to create and create the configuration for it accordingly. New Window from the menu or CMD+N will still create your default new window, but the new window button will now create the UI from your new storyboard.

And tada:

enter image description here

Upvotes: 33

Related Questions