Macos 以编程方式设置NSWindow Size';行不通
我是macOS新手,有一个非常简单的项目,在ViewController中只有一个标签。在WindowController中,我尝试使用以下代码设置窗口的大小:Macos 以编程方式设置NSWindow Size';行不通,macos,nswindowcontroller,Macos,Nswindowcontroller,我是macOS新手,有一个非常简单的项目,在ViewController中只有一个标签。在WindowController中,我尝试使用以下代码设置窗口的大小: import Cocoa class WindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() if let window = window, let screen = NSSc
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)
但是,窗口不受影响,即无论我输入什么宽度/高度,它都保持不变。如果我用鼠标改变尺寸,下次打开它时,正好是原来的尺寸
你知道我在故事板或其他地方错过了什么吗?在我看来,我忘记了一些东西,因为它是如此的基本。。。。。
(标签约束在顶部、左侧、右侧)
多亏了PUTTIN找到了它 神奇的是,把它放在主线上
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)")
}
}
现在它工作了 。。。没有加载
// 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上,它不工作。(nil refs…thx,但它似乎可以工作,只使用主线程…(奇怪)除了在主线程上执行UI更新(如苹果要求…)之外,您不能在didLoad上调用它,因为“w=self.view.window”。在didLoad上是NIL。主线程是神奇的东西还是异步调度?
windowDidLoad
是否总是在主线程上调用?不,不是。这就是它的工作方式,你期望什么?我期望主线程上的windowDidLoad
。我没想到在一个非常简单的项目中会出现另一个线程。我希望订单能解决问题。