简体   繁体   中英

Set NSWindow Size programmatically doesn't work

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, ie 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)

在此处输入图片说明

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM