Search code examples
cocoaswiftnswindowmakekeyandordertofront

How to display NSWindow within the main window in Cocoa?


I want to show a new window when an user taps on a button in the main window, but when I called the separate window using makeKeyAndOrderFront, the window popped up far away from the main window.

Here's what I wrote, in a subclass of NSViewController:

myWindow = NSWindow()
myWindow.setFrame(myView.frame, display: true)
myWindow.contentView = myView
myWindow.makeKeyAndOrderFront(self)

However, this opens a new window outside of the main window. I want to display it within the main window, possibly in the center of the main window (I set the .frame value of myView to be positioned on the center).

So how can I call the new window within the main window? In other words, can I specify where the new window shows up?


Solution

  • You'll need to convert the coordinates and or rect to screen space. NSView and NSWindow provide methods that begin with "convert" take a look at those. Sometimes you'll need to chain to convert from view space to window then window to screen. Keep in mind that a window has an NSScreen screen method and that a window could appear on many different size screens and potentially span multiple screens.