Set NSWindow Size programmatically

余生长醉 提交于 2019-12-02 20:40:41

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

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;

Swift version

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

Use setFrame:display:animate:

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

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)

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)

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!