Define macOS window size using SwiftUI

Viewed 24100

I'm using SwiftUI to develop a new macOS application and can't figure out how to define the window size. In the AppDelegate, the window size is defined as shown below:

// --- AppDelegate.swift ---

import Cocoa
import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var window: NSWindow!


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")

        window.contentView = NSHostingView(rootView: ContentView())

        window.makeKeyAndOrderFront(nil)
    }
}

The ContentView is defined as follows:

// --- ContentView.swift ---

import SwiftUI

struct ContentView : View {
    var body: some View {
        VStack {
            Spacer()
            Text("Top Text")
            Spacer()
            Text("Bottom Text")
            Spacer()
        }
    }
}

When I build and run the application, the window appears but it is not the correct size. It appears as roughly the size of the two text labels which is not the 480x300 size that is defined in the AppDelegate.

How am I supposed to define window size for a Mac application when using SwiftUI?

3 Answers

At times, the behaviour can be confusing. That is because once you run your app at least once, if you then manually resize and reposition your window, the sizes specified in the delegate will no longer matter.

Applications remember when a user has resized the window and will use the information stored in the UserDefaults instead, under the key "NSWindow Frame Main Window". If you would like to reset it, you need to wipe it out with the defaults command.

Now that that is out of the way, the reason why your window was so narrow is as follow:

With SwiftUI, not all views are created equal. For example: Text() is humble. It will only take as much space as needed. While other views, such as Spacer(), will expand as much as their parents offer (I call them greedy).

In your case, you have a VStack, with Spacer() in it. This means that the VStack fill expand to fill the height offered by its parent. In this case, the 300 pt from the delegate (or whatever is stored in the UserDefaults).

On the other hand, since you do not have any Spacer() inside a HStack, the ContentView will only expand horizontally to what it needs. That is, as wide as the widest Text() view. If you add HStack { Spacer() } inside the VStack, your content view will expand to occupy the 480 pt specified in the delegate (or whatever is stored in the UserDefaults). No need to set a frame().

The other approach (specifying a frame for the ContentView), is basically telling your ContentView to be 480x300, no matter what. In fact, if you do so, you will not be able to resize the window!

So now you know and I think it is clear... but, here's something that can be very useful to you:

There's another greedy view that may assist you in debugging your window sizes: GeometryReader. This view will always take as much as offered. Run this example, and you will know exactly how much space is offered at app launch:

struct ContentView : View {
    var body: some View {
        GeometryReader { geometry in
            VStack {
                Text("\(geometry.size.width) x \(geometry.size.height)")
            }.frame(width: geometry.size.width, height: geometry.size.height)
        }
    }
}

I have written an extensive article about GeometryReader, I recommend you check it out: https://swiftui-lab.com/geometryreader-to-the-rescue/

By the way, my AppDelegate looks like this:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Insert code here to initialize your application
    window = NSWindow(
        contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
        styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
        backing: .buffered, defer: false)
    window.center()
    window.setFrameAutosaveName("Main Window")
    window.contentView = NSHostingView(rootView: ContentView())
    window.makeKeyAndOrderFront(nil)
}

UPDATE (macOS Catalina - Beta 3)

Since the Beta3, the initial ContentView of a new project, uses maxWidth and maxHeight. A clever alternative.

struct ContentView : View {
    var body: some View {
        Text("Hello World")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

I did do it this way. It got a startup size and resizable.

struct windowSize {
// changes let to static - read comments
static minWidth : CGFloat = 100
static minHeight : CGFloat = 200
static maxWidth : CGFloat = 200
static maxHeight : CGFloat = 250
}

struct ContentView : View {
  var body: some View {
    Group() {
        VStack {
            Text("Hot Stuff")
            .border(Color.red, width: 1)
            Text("Hot Chocolate")
            .border(Color.red, width: 1)
        }
    }
    .frame(minWidth: windowSize().minWidth, minHeight: windowSize().minHeight)
    .frame(maxWidth: windowSize().maxWidth, maxHeight: windowSize().maxHeight)
    .border(Color.blue, width: 1)
  }
}

A suggested edit place here after.

enum WindowSize {
    static let min = CGSize(width: 100, height: 200)
    static let max = CGSize(width: 200, height: 250)
}

struct ContentView: View {
    var body: some View {
        Group {
            VStack {
                Text("Hot Stuff")
                    .border(Color.red, width: 1)
                Text("Hot Chocolate")
                    .border(Color.red, width: 1)
            }
        }
        .frame(minWidth: WindowSize.min.width, minHeight: WindowSize.min.height)
        .frame(maxWidth: WindowSize.max.width, maxHeight: WindowSize.max.height)
        .border(Color.blue, width: 1)
    }
}

SwiftUI

You could easily use ( compiler directives ) in the main Struct in my case, I used it to detect which screen app is running as I'm developing a multi-platform app ( iPhone, iPad , mac )

import SwiftUI

@main
struct DDStoreApp: App {
    var body: some Scene {
        WindowGroup {
            // use compiler directives #if to detect mac version or ios version
            #if os(macOS)
            // use min wi & he to make the start screen 800 & 1000 and make max wi & he to infinity to make screen expandable when user stretch the screen 
            ContentView().frame(minWidth: 800, maxWidth: .infinity, minHeight: 1000, maxHeight: .infinity, alignment: .center)
            #else
            ContentView()
            #endif
        }
    }
}
Related