如何(以编程方式)设置主窗口的位置和大小? [英] How to set the position and size (programmatically) for the main window?
问题描述
我正在使用OS X的最新默认项目(10.11,Xcode 7.0).它使用情节提要板,层次结构如下:
I'm using the newest default project for OS X (10.11, Xcode 7.0). It uses storyboards and the hierarchy is as follows:
Window Controller -> View Controller
我想设置窗口的初始位置和框架尺寸.显然,用户可以更改它,但是我希望它以一些默认值开始.我尝试了子类化NSWindowController
,但这没有效果.
I want to set the initial position and frame size for the window. Obviously the user can change that, but I want it to start with some defaults. I've tried subclassing NSWindowController
, but that has no effect.
class WindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
guard let window = window else {
return
}
let windowOriginPoint = CGPoint(x: 0, y: 0)
let windowSize = CGSize(width: 800, height: 400)
window.setFrame(NSRect(origin: windowOriginPoint, size: windowSize), display: true)
print("windowDidLoad")
}
}
执行此操作的正确方法是什么?
What's the proper way of doing this?
推荐答案
我遇到了同样的问题.我通过将setFrame
代码移到windowDidBecomeMain
而不是windowDidLoad
来解决了;如果将窗口手动移动并重新选择为主窗口,则会产生严重的副作用:拖动窗口时会跳转并立即返回到正确的位置.为了避免这种情况,我使用了一个补丁:在windowController
中,我声明了一个
I faced the same problem. I solved it by moving the setFrame
code inside windowDidBecomeMain
instead of windowDidLoad
; there is a bad side effect if the window has been moved manually and is reselected to become main: window jumps when dragged and immediately returns to the right position. To avoid it, I used a patch: In the windowController
, I declare a
private var firstAppearance = true;
在windowDidBecomeMain
中,我仅在firstAppearance
上执行setFrame;然后将firstAppearance
设置为false.
In the windowDidBecomeMain
I do the setFrame only on firstAppearance
; then I set firstAppearance
to false.
这篇关于如何(以编程方式)设置主窗口的位置和大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!