5

What Swift code will switch the app to fullscreen? I found references with example code for IOS. I am looking for a code which works for a MacOS app.

FJC
  • 213
  • 2
  • 9

3 Answers3

10

Updated for Swift 4

override func viewDidAppear() {
    let presOptions: NSApplication.PresentationOptions = [.fullScreen, .autoHideMenuBar]
    let optionsDictionary = [NSView.FullScreenModeOptionKey.fullScreenModeApplicationPresentationOptions: presOptions]
    view.enterFullScreenMode(NSScreen.main!, withOptions: optionsDictionary)
    view.wantsLayer = true
}
possen
  • 8,596
  • 2
  • 39
  • 48
4

One way is to override viewDidAppear in NSViewController:

class ViewController : NSViewController {

    override func viewDidAppear() {
        let presOptions: NSApplicationPresentationOptions = ([.FullScreen,.AutoHideMenuBar])   
        let optionsDictionary = [NSFullScreenModeApplicationPresentationOptions :
            NSNumber(unsignedLong: presOptions.rawValue)]
        self.view.enterFullScreenMode(NSScreen.mainScreen()!, withOptions:optionsDictionary)
        self.view.wantsLayer = true
        }
}

Apple Developer API Reference : viewDidAppear()

l'L'l
  • 44,951
  • 10
  • 95
  • 146
3

An alternative, if you want different behavior, where the menu bar is available when you move your mouse to top is this. However, it starts out as a normal size window then grows, so that may not be desirable depending on what you are doing.

override func viewDidAppear() {
    view.window?.toggleFullScreen(self)
}
possen
  • 8,596
  • 2
  • 39
  • 48
  • That's much better answer, because in the accepted one the aplication in fullscreen locks everything in MacOS, you can't resize thw window, there is no menu bar appearing and even Command + Tab keys won't work! If you change system volume the indicator won't display either! – Heitor Jun 01 '19 at 03:54
  • How can I exit to full screen? with a button in the view – Krunal Nagvadia Dec 29 '20 at 11:36