Objective-c – Cocoa window position anomaly

cocoanswindowobjective c

I have a weird problem with positioning a window on screen. I want to center the window on the screen, but i don't know how to do that. Here's what i've got. The window is created from nib by the main controller:

IdentFormController *ftf = [[IdentFormController alloc] initWithWindowNibName:@"IdentForm"];
[[ftf window] makeKeyAndOrderFront:self];

Now the IdentFormController has awakeFromNib() method in which it tries to position the window. For the sake of simplicity i've just tried to do setFrameOrigin(NSMakePoint(0, 0)). What happens is as follows:

The first time i create this window, everything works as expected. But if i create it again after releasing the previous, it starts appearing at random positions. Why does it do that?

Best Answer

So as I understand it you want to center the window on the screen?

Well assuming NSWindow *window is your window object then there are two methods...

[window center];

This is the best way to do it but it will ofset to take into account visual weight and the Dock's presence.

If you want dead center then this would work...

// Calculate the actual center
CGFloat x = (window.screen.frame.size.width - window.frame.size.width) / 2;
CGFloat y = (window.screen.frame.size.height - window.frame.size.height) / 2;

// Create a rect to send to the window
NSRect newFrame = NSMakeRect(x, y, window.frame.size.width, window.frame.size.height);

// Send message to the window to resize/relocate
[window setFrame:newFrame display:YES animate:NO];

This code is untested but it gives you a fair idea of what you need to do to get this thing working the way you want, personally I would advise you stick with Apple's code because it has been tested and is what the user would expect to see, also from a design perspective as a designer my self I don't always rely on the actual center to be where the optical center is.