Content size of NSWindow returns zero frame after setting view on macOS 15.0 and xCode 16.1

I would like to show a nswindow at a position on screen base on height of the nswindow and its content view. I received zero width and height on macOS 15.0 and xCode 16.1 however they were returned correct width and height on previous macOS version.

import Cocoa
import SwiftUI

class AppDelegate: NSObject, NSApplicationDelegate {
    
    private var window: NSWindow!
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        window = NSWindow(
            contentRect: .zero,
            styleMask: [.miniaturizable, .closable, .resizable],
            backing: .buffered, defer: false)
        
        window.title = "No Storyboard Window"
        window.contentView = NSHostingView(rootView: ContentView()) // a swiftui view
        window.center()
        let windowFrame = window.frame
        print("window Frame \(windowFrame)") // print width and height zero here
        window.makeKeyAndOrderFront(nil)
    }   
}

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .padding()
    }
}

I tried window.layoutIfNeeded() after setting contentview but it didn't work

How can I get the frame after setting contentview for nswindow on macOS 15.0?

Answered by Frameworks Engineer in 812231022

Hello,

This is a behavior change we made for apps that target the macOS 15 SDK, NSHostingView will now be more lazy in when it decides to size it's containing window.

For use cases like yours, where you need the window to have the correct initial size before calling center(), you can call updateConstraintsIfNeeded():

For example:

window.contentView = NSHostingView(rootView: ContentView())
window.updateConstraintsIfNeeded()
window.center()
Accepted Answer

Hello,

This is a behavior change we made for apps that target the macOS 15 SDK, NSHostingView will now be more lazy in when it decides to size it's containing window.

For use cases like yours, where you need the window to have the correct initial size before calling center(), you can call updateConstraintsIfNeeded():

For example:

window.contentView = NSHostingView(rootView: ContentView())
window.updateConstraintsIfNeeded()
window.center()
Content size of NSWindow returns zero frame after setting view on macOS 15.0 and xCode 16.1
 
 
Q