How can I easily save the Window size and position state using Obj-C?

前端 未结 9 516
灰色年华
灰色年华 2021-02-02 09:19

What is the best way to remember the Windows position between application loads using Obj-C? I am using Interface Builder for the interface, is it possible to do this with bind

9条回答
  •  鱼传尺愫
    2021-02-02 09:42

    I tried all the solutions. It can only saves the position, not the size. So we should do that manually. This is how I do it on my GifCapture app https://github.com/onmyway133/GifCapture

    class MainWindowController: NSWindowController, NSWindowDelegate {
    
      let key = "GifCaptureFrameKey"
    
      override func windowDidLoad() {
        super.windowDidLoad()
    
        NotificationCenter.default.addObserver(self, selector: #selector(windowWillClose(_:)), name: Notification.Name.NSWindowWillClose, object: nil)
      }
    
      override func awakeFromNib() {
        super.awakeFromNib()
    
        guard let data = UserDefaults.standard.data(forKey: key),
          let frame = NSKeyedUnarchiver.unarchiveObject(with: data) as? NSRect else {
            return
        }
    
        window?.setFrame(frame, display: true)
      }
    
      func windowWillClose(_ notification: Notification) {
        guard let frame = window?.frame else {
          return
        }
    
        let data = NSKeyedArchiver.archivedData(withRootObject: frame)
        UserDefaults.standard.set(data, forKey: key)
      }
    }
    

提交回复
热议问题