如何以编程方式设置窗口大小?我在IB中有一个窗口,我想在我的代码中设置它的大小以使其更大。
使用-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
实际上似乎需要反转+/-以防止窗口在屏幕上移动:
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;
Swift版本
var frame = self.view.window?.frame
frame?.size = NSSize(width: 400, height:200)
self.view.window?.setFrame(frame!, display: true)
[window setFrame:NSMakeRect(0.f, 0.f, 200.f, 200.f) display:YES animate:YES];
我的两分钱为swift 4.x 7 OSX:
a)不要调用viewDidLoad b)进入主队列... b)等待一段时间...例如使用:
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)
}
}
通常我想根据内容的大小(不包括标题栏)调整窗口大小:
var rect = window.contentRect(forFrameRect: window.frame)
rect.size = myKnownContentSize
let frame = window.frameRect(forContentRect: rect)
window.setFrame(frame, display: true, animate: true)