7

Is there any way to center a window in the center of the screen in OSX?

I am using the code below but it changes just the size but not the position on screen.

override func viewDidLoad() {
        super.viewDidLoad()

        let ScreenStart = NSSize(width: (NSScreen.mainScreen()?.frame.width)! / 1.5, height: (NSScreen.mainScreen()?.frame.height)! / 1.5)

        self.view.frame.size = ScreenStart
        self.view.frame.origin = NSPoint(x: (NSScreen.mainScreen()?.frame.origin.x)!/2, y: (NSScreen.mainScreen()?.frame.height)! / 2)  
    }
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
SNos
  • 3,430
  • 5
  • 42
  • 92

2 Answers2

16

For future references this is done inside NSWindowController class using self.window?.center()

SNos
  • 3,430
  • 5
  • 42
  • 92
1

I had the same question, when using a Modal presentation of a NSTabViewController.

I like this answer: How to constrain second NSViewController minimum size in OS X app?

I used NSWindowDelegate to access the NSWindow properties and functions. This included self.view.window?.center() as @SNos said.

class YDtabvc: NSTabViewController, NSWindowDelegate {

    public let size = NSSize(width: 500, height: 800)

    override func viewWillAppear() {
        super.viewWillAppear()
        self.view.window?.delegate = self
        self.view.window?.minSize = size
        self.view.window?.center()

    }
    override func viewDidAppear() {
        super.viewDidAppear()
        var frame = self.view.window!.frame
        frame.size = size
        self.view.window?.setFrame(frame, display: true)
    }
}

rustyMagnet
  • 3,479
  • 1
  • 31
  • 41