我是macOS的新手,并且有一个非常简单的项目,在ViewController中只有一个标签。在WindowController中,我尝试使用该代码设置窗口的大小:
import Cocoa
class WindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
if let window = window, let screen = NSScreen.main {
let screenRect = screen.visibleFrame
print("screenRect \(screenRect)")
window.setFrame(NSRect(x: screenRect.origin.x, y: screenRect.origin.y, width: screenRect.width/2.0, height: screenRect.height/2.0), display: true, animate: true)
print("windowFrame \(window.frame)")
}
}
}
日志显示:
screenRect (0.0, 30.0, 1680.0, 997.0)
windowFrame (0.0, 30.0, 840.0, 499.0)
但是,该窗口不会受到影响,即我输入的宽度/高度都保持不变。如果我用鼠标更改大小,下次打开时,将完全使用旧大小。
有什么主意,我可能会在分镜脚本或其他任何地方错过什么?在我看来,我忘记了一些东西,因为它是如此基本..... (标签限制在顶部,左侧,右侧)
答案 0 :(得分:0)
...确实加载了...
// decide if needed..
let when = DispatchTime.now() + 0.5
DispatchQueue.main.asyncAfter(deadline: when, execute: { [weak self] in
self?.setSize()
})
} //setupUI
private final func setSize(){
if let w = self.view.window{
var frame = w.frame
frame.size = NSSize(width: 800, height: 600)
w.setFrame(frame, display: true, animate: true)
}
}
注意:在didLoad上没有一点延迟,它不起作用。 (无裁判...)
答案 1 :(得分:-1)
找到了它,这要感谢PUTTIN Why NSWindow animator setFrame:display:animate: didn't work sometimes?
神奇的是,将其放置在mainThread上
DispatchQueue.main.async {
window.setFrame(NSRect(x: screenRect.origin.x, y: screenRect.origin.y, width: screenRect.width/1.0, height: screenRect.height/1.0), display: true, animate: true)
print("windowFrame \(window.frame)")
}
}
现在可以了!