Reputation: 3470
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)
}
Upvotes: 8
Views: 6975
Reputation: 4105
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)
}
}
Upvotes: 1
Reputation: 3470
For future references this is done inside NSWindowController
class using self.window?.center()
Upvotes: 17