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.
Asked
Active
Viewed 3.2k times
6 Answers
35
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

Jonathan Grynspan
- 43,286
- 8
- 74
- 104
-
1@Leo's answer has a point, or at least I saw the same thing - the +/- should be reversed. – Nikolay Tsenkov Apr 25 '14 at 13:28
-
1i have try this code but still my window moving downwards. any solution to stop moving window. – princ___y May 27 '16 at 05:15
-
Works perfectly for me. I wanted to programmatically resize a window controller that was being presented as a sheet view. Thanks! – Supertecnoboff Aug 17 '17 at 09:57
-
please note that immediate size change in viewDidAppear() would not work, put timer or something else... – Mushrankhan Jun 25 '22 at 18:31
12
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;

Leo
- 790
- 8
- 10
-
2Or better still: frame.origin.y += (frame.size.height - theSizeYouWant.height); – mojuba Aug 06 '15 at 16:06
7
Swift version
var frame = self.view.window?.frame
frame?.size = NSSize(width: 400, height:200)
self.view.window?.setFrame(frame!, display: true)

kj13
- 1,765
- 1
- 11
- 14
4
[window setFrame:NSMakeRect(0.f, 0.f, 200.f, 200.f) display:YES animate:YES];
4
Usually I want to resize the window based on the size of the content (not including the title bar):
var rect = window.contentRect(forFrameRect: window.frame)
rect.size = myKnownContentSize
let frame = window.frameRect(forContentRect: rect)
window.setFrame(frame, display: true, animate: true)

Robin Stewart
- 3,147
- 20
- 29
-
-
`myKnownContentSize` is just whatever size I want for my window contents. This code snippet then makes the window itself a corresponding size that accommodates the title bar (or other future OS additions). – Robin Stewart Jul 23 '19 at 18:18
0
my two cents for swift 4.x 7 OSX:
a) do not call on viewDidLoad b) go on main queue... b) wait some time... so for example use:
private final func setSize(){
if let w = self.view.window{
var frame = w.frame
frame.size = NSSize(width: 400, height: 800)
w.setFrame(frame, display: true, animate: true)
}
}

ingconti
- 10,876
- 3
- 61
- 48