我如何以编程方式设置窗口大小?我在IB中有一个窗口,我想在我的代码中设置它的大小,使其更大。
我如何以编程方式设置窗口大小?我在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)
使用setFrame:display:animate:
方法。
[window setFrame:NSMakeRect(0.f, 0.f, 200.f, 200.f) display:YES animate:YES];
通常我希望根据内容的大小(不包括标题栏)来调整窗口的大小:
var rect = window.contentRect(forFrameRect: window.frame)
rect.size = myKnownContentSize
let frame = window.frameRect(forContentRect: rect)
window.setFrame(frame, display: true, animate: true)
myKnownContentSize
的? - rustyMagnetmyKnownContentSize
只是我想要的窗口内容的大小。然后,这段代码使窗口本身具有相应的大小,以适应标题栏(或其他未来的操作系统添加)。 - Robin Stewart关于Swift 4.x和OSX的建议:
a) 不要在viewDidLoad中调用 b) 进入主队列... c) 等待一段时间...例如使用:
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)
}
}