以编程方式设置 NSWindow Size 不起作用

2024-01-13

我是 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)

但是,窗口不受影响,即无论我输入什么宽度/高度,它都保持不变。如果我用鼠标更改大小,下次打开它时,将完全是旧大小。

知道我在故事板或其他地方可能错过了什么吗?在我看来,我忘记了一些东西,因为它是如此基本...... (标签约束为上、左、右)


找到了,感谢 PUTTIN为什么 NSWindow 动画器 setFrame:display:animate: 有时不起作用? https://stackoverflow.com/questions/16166338/why-nswindow-animator-setframedisplayanimate-didnt-work-sometimes

神奇的是,将它放在主线程上

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)")
    }
}

现在可以了!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式设置 NSWindow Size 不起作用 的相关文章

随机推荐