简体   繁体   中英

Initial NSWindow size as percentage of screen size

I would like to set my NSWindow size as a function of the screen size.

There is an option in Interface Builder to set it in points, but not as a function of the screen size.

How can I set it programmatically as a default?

Note that I still want UI preservation to restore its size from previous session if such state is available.

Well, you can get the screen's size, and just apply a little math to it to get this working. Set the dimensions of the window to the screens dimensions multiplied by the percentage of the screen you would like the window to take up. Going a step further, you can do this and keep the window centered by multiplying its origin by (1-percentage)/2.0.

NSRect screenSize = [[NSScreen mainScreen] frame];

CGFloat percent = 0.6;

CGFloat offset = (1.0 - percent) / 2.0;

[self.window setFrame:NSMakeRect(screenSize.size.width * offset, screenSize.size.height * offset, screenSize.size.width * percent, screenSize.size.height * percent) display:YES];

Taking 0x7fffffff's great answer a bit further: here's a complete solution in Swift that works with autosaving. Tested with XCode 7 Beta 6.

In interface builder, set the window class to MainWindow and specify an Autosave name in the attributes inspector of the window. The following code sets the window coordinates only when no autosave information exist yet, ie the window is displayed for the first time. After that (for example after app relaunch) the window is restored to it's last position and size.

class MainWindow: NSWindow {

    var didInitialResize = false

    override func awakeFromNib() {
        super.awakeFromNib()

        let defaults = UserDefaults.standard
        if !didInitialResize && defaults.object(forKey: "NSWindow Frame \(frameAutosaveName)") == nil {
            didInitialResize = true

            let screenSize = NSScreen.main!.frame

            let percent = CGFloat(0.90)
            let offset: CGFloat = CGFloat((1.0 - percent) / 2.0)

            setFrame(NSMakeRect(
                screenSize.size.width * offset,
                screenSize.size.height * offset,
                screenSize.size.width * percent,
                screenSize.size.height * percent),
                     display: true)
        }
    }
}

Btw.. the autosave information is saved in the app's preferences file. For testing it might be helpful to do rm ~/Library/Preferences/myapp.plist; sudo killall cfprefsd rm ~/Library/Preferences/myapp.plist; sudo killall cfprefsd to delete the autosave information.

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