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

前端 未结 9 518
灰色年华
灰色年华 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:37

    Based on onmyway133's answer I wrote a RestorableWindowController class. As long as your window controller inherits from it, position and size for your windows are restored.

    import Cocoa
    
    open class RestorableWindowController: NSWindowController {
    
        // MARK: - Public -
    
        open override func windowDidLoad() {
            super.windowDidLoad()
    
            NotificationCenter.default.addObserver(self, selector: #selector(windowWillClose), name: NSWindow.willCloseNotification, object: nil)
            if let frame = storedFrame {
                window?.setFrame(frame, display: true)
            }
        }
    
        open override func awakeFromNib() {
            super.awakeFromNib()
    
            if let frame = storedFrame {
                window?.setFrame(frame, display: true)
            }
        }
    
        open override var contentViewController: NSViewController? {
            didSet {
                if let frame = storedFrame {
                    window?.setFrame(frame, display: true)
                }
            }
        }
    
        // MARK: - Private -
    
        private var storedFrameKey: String {
            String(describing: type(of: self)) + "/storedFrameKey"
        }
        private var storedFrame: NSRect? {
            guard let string = UserDefaults.standard.string(forKey: storedFrameKey) else {
                return nil
            }
            return NSRectFromString(string)
        }
    
        @objc private func windowWillClose() {
            guard let frame = window?.frame else {
                return
            }
            UserDefaults.standard.set(NSStringFromRect(frame), forKey: storedFrameKey)
        }
    
    }
    

提交回复
热议问题