SwiftUI window aspect ratio

Is there a way to force a window to resize according to an aspect ratio? This is possible in AppKit via the NSWindow.contentAspectRatio property but I cannot find something similar for SwiftUI.

Basically, I want the window to maintain the aspect ratio of its contents.

Post not yet marked as solved Up vote post of Lucky7 Down vote post of Lucky7
1.7k views

Replies

I've tried setting contentAspectRatio from SwiftUI via NSApplication.shared.keyWindow?.contentAspectRatio = ratio which might be an acceptable hack for me -- but it looks like it's behaving more like aspectRatio, where the window title is included in the titlebar. Not sure how to get the aspect ratio to only limit the SwiftUI content.

  • Ah the other gotcha is you may want to call window.styleMask.remove(.fullSizeContentView), otherwise the content area includes the title bar (which SwiftUI can layout in using .ignoreSafeAreas())

Add a Comment

Another solution that seems to work is to use NSViewControllerRepresentable to create a NSViewController based view. When viewDidAppear is called, you can set the NSWindowDelegate to self to receive window events and set the aspect ratio.

Here's another good one that would work better with multiple windows:

Use a NSViewRepresentable to get binding for NSWindow as in this StackOverflow answer: https://stackoverflow.com/a/63439982

And in order for contentAspectRatio to exclude the title bar, you must also call window.styleMask.remove(.fullSizeContentView)

Ending up with something like:

struct Example: App {
  @State private var window: NSWindow?
  var body: some Scene {
    WindowGroup {
      ContentView()
        .background(WindowAccessor(window: $window))
        .onChange(of: window) { newWindow in
          newWindow?.styleMask.remove(.fullSizeContentView) // Exclude title bar from content area
          newWindow?.contentAspectRatio = desiredAspectRatio
        }
    }
  }

Is NSWindow Cocoa? I can’t import it in Swift Playgounds.

Is there another way to set contentAspectRatio for SwiftUI apps?