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

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

    Got sick and tired of Apples AutoSave and IB BS which sometimes does and sometimes doesn't work and depends on flag settings in System Prefs blah blah blah. Just do this, and it ALWAYS WORKS and even remembers users full screen state!

    -(void)applicationDidFinishLaunching:(NSNotification *)notification
    {
        [_window makeKeyAndOrderFront:self];
    
        // Because Saving App Position and Size is FUBAR
        NSString *savedAppFrame = [userSettings stringForKey:AppScreenSizeAndPosition];
        NSRect frame;
        if(savedAppFrame) {
            frame = NSRectFromString(savedAppFrame);
            [_window setFrame:frame display:YES];
        }
        else
            [_window center];
    
        // Because saving of app size and position on screen doesn't remember full screen
        if([userSettings boolForKey:AppIsFullScreen])
            [_window toggleFullScreen:self];
    }
    -(void)windowDidEnterFullScreen:(NSNotification *)notification
    {
        [userSettings setBool:YES forKey:AppIsFullScreen];
    }
    -(BOOL)windowShouldClose:(NSWindow *)sender
    {
        // Have to use this to set zoom state because exit full screen state always called on close
        if(sender == _window) {
            [userSettings setBool:(_window.isZoomed ? YES:NO) forKey:AppIsFullScreen];
        }
        return YES;
    }
    -(void)applicationWillTerminate:(NSNotification *)aNotification
    {
        [userSettings setObject:NSStringFromRect(_window.frame) forKey:AppScreenSizeAndPosition];
        [userSettings synchronize];
    }
    

提交回复
热议问题