Search code examples
objective-cxcode4nsviewnswindow

Problem with Position of NSWindow after changing the ContenView


in my application i hav one NSWindow and different CustomViews... my target is just to change the contenView of the window. i placed the main window in the center of the screen with a button and after pressing the button the following code is executed

[mainWindow setFrame:[mainView frame] display:TRUE animate:TRUE];
[mainWindow setContentView:mainView];

this just works fine but after resizing the window is in the left bottom corner of the screen.. i want it to stay in the center of the screen

when i use

[mainWindow center];

it will move to the left bottom corner and after resizing it jumps to to center.. that not good at all it should just stay in the middle of the screen


Solution

  • The reason your window moves to the bottom-left corner is that [mainWindow setFrame:[mainView frame] display:YES animate:YES]; The [mainView frame].origin is NSZeroPoint while it has no superview. If you want your window to stay centered, you need to setFrameOrigin:. I recommend using NSMidX() and NSMidY() to calculate the offset from the screen's center.