以编程方式设置NSWindow大小

时间:2012-09-15 14:32:38

标签: objective-c macos window size nswindow

如何以编程方式设置窗口大小?我在IB中有一个窗口,我想在我的代码中设置它的大小以使其更大。

5 个答案:

答案 0 :(得分:27)

使用-setFrame:display:animate:获得最大控制权:

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

请注意,窗口坐标会从您可能习惯的位置翻转过来。矩形的原点位于OS X上Quartz / Cocoa的左下角。确保原点保持不变:

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

答案 1 :(得分:10)

实际上似乎需要反转+/-以防止窗口在屏幕上移动:

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;

答案 2 :(得分:3)

Swift版

var frame = self.view.window?.frame
frame?.size = NSSize(width: 400, height:200)
self.view.window?.setFrame(frame!, display: true)

答案 3 :(得分:2)

使用setFrame:display:animate:

[window setFrame:NSMakeRect(0.f, 0.f, 200.f, 200.f) display:YES animate:YES];

答案 4 :(得分:0)

通常,我想根据内容的大小(不包括标题栏)来调整窗口的大小:

var rect = window.contentRect(forFrameRect: window.frame)
rect.size = myKnownContentSize
let frame = window.frameRect(forContentRect: rect)
window.setFrame(frame, display: true, animate: true)