Set NSWindow Size programmatically doesn't wor

2019-08-16 16:32发布

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

The log shows:

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.

enter image description here

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)

enter image description here

2条回答
ゆ 、 Hurt°
2楼-- · 2019-08-16 16:54

... did load...

   // 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)

    }
}

note: on didLoad without a small delay it does not work. (nil refs...)

查看更多
劫难
3楼-- · 2019-08-16 16:58

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

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

Now it works!

查看更多
登录 后发表回答