How to set the position and size (programmatically) for the main window?
Asked Answered
E

1

7

I'm using the newest default project for OS X (10.11, Xcode 7.0). It uses storyboards and the hierarchy is as follows:

Window Controller -> View Controller

I want to set the initial position and frame size for the window. Obviously the user can change that, but I want it to start with some defaults. I've tried subclassing NSWindowController, but that has no effect.

  class WindowController: NSWindowController {

     override func windowDidLoad() {
        super.windowDidLoad()

        guard let window = window else {
           return
        }

        let windowOriginPoint = CGPoint(x: 0, y: 0)
        let windowSize = CGSize(width: 800, height: 400)
        window.setFrame(NSRect(origin: windowOriginPoint, size: windowSize), display: true)

        print("windowDidLoad")
     }

  }

What's the proper way of doing this?

Emmalynn answered 1/10, 2015 at 8:9 Comment(3)
Have you connected the window controller to your storyboard?Lascivious
By "connected", do you mean have I set the class name in the attributes inspector to the name of my class? I have.Emmalynn
I will take a deeper look into thisLascivious
A
2

I faced the same problem. I solved it by moving the setFrame code inside windowDidBecomeMain instead of windowDidLoad; there is a bad side effect if the window has been moved manually and is reselected to become main: window jumps when dragged and immediately returns to the right position. To avoid it, I used a patch: In the windowController, I declare a

private var firstAppearance = true;

In the windowDidBecomeMain I do the setFrame only on firstAppearance; then I set firstAppearance to false.

Anatropous answered 27/4, 2016 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.