Mozzak
Mozzak

Reputation: 211

MAC Cocoa - Programmatically set window size

I have a one window application that has some checkboxes on the screen.

I use NSUserDefaults to store not only the state of the checkboxes but also the main window width, height, and position (x/y).

My issue is to find the right event to read and set the window properties.

Currently I do it at:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// read preferences
UserPreferences *userPrefs = [[UserPreferences alloc] init];  
NSRect oldFrame = [window frame];  
if( [userPrefs MainWindowWidth] > 0)
    oldFrame.size.width = [userPrefs MainWindowWidth];

if( [userPrefs MainWindowHeight] > 0)
    oldFrame.size.height = [userPrefs MainWindowHeight];

if( [userPrefs MainWindowTop] > 0)
    oldFrame.origin.y = [userPrefs MainWindowTop];

if( [userPrefs MainWindowLeft] > 0)
    oldFrame.origin.x = [userPrefs MainWindowLeft];

// set windows properties
[window setFrame:oldFrame display:YES animate:NO];
}

It works but the screen first shows default size and then changes to the stored size so visually a hiccup. This tells me that its too late in the event chain to set these parameters.

I also tried awakefromnib but that seems too early in the chain since setting width and height is simply ignored.

Which event would be the right one to plug this code in to reset the window right before it is show on screen?

Any advise would be appreciated. Every beginning is hard.

thank you.

Upvotes: 0

Views: 2205

Answers (2)

zeppenwolf
zeppenwolf

Reputation: 345

The applicationDidFinishLaunching function is a place to do things, well... as soon as the app has finished launching. But what you really want is to catch the window at the time when it has just been loaded from the nib, but before it has shown. IOW, you're trying to do this in the wrong place.

You need more control over your window, so... create your own window controller! Create your own class which inherits from NSWindowController, say MyWindTrol. In the implementation file, add the awakeFromNib function, and put your efforts to control your window's size and location in there.

In your nib file, drag an NSObject from the library, declare it to be of class MyWindTrol, and control-drag the connections so that your MyWindTrol object's window property points to the window object.

Upvotes: 0

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

This is because window's frame is first loaded from nib, and then window is shown (once finished loading from nib).

You can disable 'show window on start' checkbox in interface builder, and show it manually in applicationDidFinishLaunching.

Upvotes: 1

Related Questions