Set NSWindow Size programmatically doesn't work

这一生的挚爱 提交于 2019-12-25 04:19:49

问题


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.

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)


回答1:


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




回答2:


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!



来源:https://stackoverflow.com/questions/55965290/set-nswindow-size-programmatically-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!