Getting the Size of a Window

If you’re creating a macOS program using storyboards, you may need to know the size of a window. To get this information, you just need to follow two steps:

  • Create an IBOutlet that represents your window. This IBOutlet should be of the type NSView
  • Use the frame.width and frame.height properties to get the width and height of the window defined by your IBOutlet

To create an IBOutlet for a window, just opens he Assistant Editor, move the mouse pointer over the window, and Control-drag to the Swift class file linked to your window such as ViewController.swift. Then release the Control key and the left mouse button to create an IBOutlet.

You can use any name for your IBOutlet, but whatever name you choose will now represent your window such as:

@IBOutlet var myWindow: NSView!

Assuming you named your window IBOutlet myWindow, you’ll be able to access the frame.width and frame.height properties like this:


If you put the following two lines of code in the viewDidLoad function that runs as soon as a window appears, you’ll see the defined width and height of the window.

print ("Window height = \(myWindow.frame.height)")
print ("Window width = \(myWindow.frame.width)")
December 21st, 2016 by
HTML Snippets Powered By :