以编程方式设置 NSWindow 大小不起作用 [英] Set NSWindow Size programmatically doesn't work

查看:68
本文介绍了以编程方式设置 NSWindow 大小不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是macOS的新手,并且有一个非常简单的项目,在ViewController中只有一个标签.在WindowController中,我尝试使用该代码设置窗口的大小:

I'm new to macOS and have a very simple project with just one label in the ViewController. In the WindowController I'm trying to set the size of the window with that code:

    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)

但是,该窗口不会受到影响,即我输入的宽度/高度都保持不变.如果我用鼠标更改大小,则下次打开时,将完全使用旧大小.

However, the window isn't affected, i.e. whatever I enter as width/height, it stay the same. If I change the size with the mouse, next time I open it, exactly the old size.

有什么主意,我可能会在情节提要或其他任何地方错过什么?在我看来,我忘了一些基本的东西.....(标签限制在顶部,左侧,右侧)

Any idea what I may missed in storyboard or anywhere else? Seems to me that I forgot something as it is so basic..... (The label is constraint to the top, left, right)

推荐答案

找到了它,这要归功于PUTTIN

Found it, thanks to PUTTIN Why NSWindow animator setFrame:display:animate: didn't work sometimes?

神奇的是,将其放置在mainThread上

The magic thing is, to have it on the 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)")
    }
}

现在可以了!

这篇关于以编程方式设置 NSWindow 大小不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆