Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set NSWindow Size programmatically

How can I set the window size programmatically? I have a window in IB and I want to set the size of it in my code to make it larger.

like image 227
atomikpanda Avatar asked Sep 15 '12 14:09

atomikpanda


3 Answers

Use -setFrame:display:animate: for maximum control:

NSRect frame = [window frame];
frame.size = theSizeYouWant;
[window setFrame: frame display: YES animate: whetherYouWantAnimation];

Note that window coordinates are flipped from what you might be used to. The origin point of a rectangle is at its bottom left in Quartz/Cocoa on OS X. To ensure the origin point remains the same:

NSRect frame = [window frame];
frame.origin.y -= frame.size.height; // remove the old height
frame.origin.y += theSizeYouWant.height; // add the new height
frame.size = theSizeYouWant;
// continue as before
like image 69
Jonathan Grynspan Avatar answered Nov 15 '22 15:11

Jonathan Grynspan


It is actually seems that +/- need to be reversed to keep window from moving on the screen:

NSRect frame = [window frame];
frame.origin.y += frame.size.height; // origin.y is top Y coordinate now
frame.origin.y -= theSizeYouWant.height; // new Y coordinate for the origin
frame.size = theSizeYouWant;
like image 12
Leo Avatar answered Nov 15 '22 15:11

Leo


Swift version

var frame = self.view.window?.frame
frame?.size = NSSize(width: 400, height:200)
self.view.window?.setFrame(frame!, display: true)
like image 6
kj13 Avatar answered Nov 15 '22 14:11

kj13