Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set position of modal window

I have a window I want to display as a modal window (OS X 10.10). I'm loading the NIB for the window and am able to set the title successfully and then display the window. But whatever I do to try to affect the window position doesn't work.

This works (part of NSWindowController sub-class):

[[self window] setTitle:title];
[[NSApplication sharedApplication] runModalForWindow:[self window]];

Here are ways with which I've tried to affect the position after setting the title:

[[self window] setFrameOrigin: NSMakePoint(200.0, 200.0) ];
[[self window] setFrameTopLeftPoint: NSMakePoint(200.0, 200.0) ];
[[self window] setFrame: NSMakeRect(200, 300, [[self window] frame].size.width, [[self window] frame].size.height) display:YES];

(I've tried other values as well - just for testing, but nothing.)

I can even query the

[[self window] frame]

and it pretends to accept the new values, but the window stubbornly keeps showing up in the same position.

What gives?

like image 274
Rene Rosendahl Avatar asked May 11 '15 04:05

Rene Rosendahl


1 Answers

I have solved this by

1- Make a new NSWindow subclass, overriding the center method, where you just make the frame of the new window positioned at whatever NSPoint you want:

class CenteredInParentWindow: NSWindow {

    var parentMinX : CGFloat?
    var parentMinY : CGFloat?

    override func center() {
        guard let parentMinX = parentMinX, let parentMinY = parentMinY else {
            super.center()
            return
        }
        self.setFrameOrigin(NSPoint(x: parentMinX, y: parentMinY))
    }
}

2 - Set WindowController's window class to be the new NSWindow subclass, in Storyboard.

3- Instatiate the window controller and set the attributes of the subclassed window

 let myWindowController = self.storyboard!.instantiateController(withIdentifier: "windowID") as! PlansWindowController
        if let customWindow = myWindowController.window as? CenteredInParentWindow {
            customWindow.parentMinX = NSApplication.shared.mainWindow?.frame.minX
            customWindow.parentMinY = NSApplication.shared.mainWindow?.frame.minY
        }
        NSApp.runModal(for: myWindowController.window!)
}

You may need runModal method for making the window a modal one. Don't forget to include NSApp.stopModal() in the windowWillClose method which is available in NSWindowDelegate in your View controller

like image 54
Newsonic Avatar answered Oct 04 '22 20:10

Newsonic