Center the main window of an app in Mac Catalyst

114 views Asked by At

It is possible to set the position on the screen of the app's main Window in UIWindowScene?

I want to center the window of my Mac Catalyst app every time the user open it (instead of appearing in the last position before the app was closed)

I believe that this fact greatly affects the usability of an application and I do not see information on the Internet.

1

There are 1 answers

0
HangarRash On

As of iOS 16, you can use UIWindowScene requestGeometryUpdate(_:errorHandler:)

I would add the following to your main window scene's root view controller:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if #available(macCatalyst 16.0, *) {
        if let winScene = self.view.window?.windowScene {
            // Calculate the new window frame
            // This takes the existing window size and position and centers it on the screen
            let screen = winScene.screen.bounds
            var frame = winScene.effectiveGeometry.systemFrame
            frame.origin.x = (screen.width - frame.width) / 2
            frame.origin.y = (screen.height - frame.height) / 2

            // Now request the new frame
            winScene.requestGeometryUpdate(.Mac(systemFrame: frame))
        }
    }
}