DEV Community

Szabolcs Toth
Szabolcs Toth

Posted on • Edited on

NSWindow without Storyboard

Time to time the debate restarts whether using Storyboard is the proper way of interface desing. On iPhone it is quite simple and you can find several articles or tutorials.
I wanted to try it on macOS and hardly found anything up-to-date information. Hereby I share what I found, maybe it can help others.

At the end of the article I indicated all the sources I used.

Step 1.
Create a new Swift project with Storyboard.
create

Step 2.
Remove the Main.Storyboard and ViewController.swift, then delete "Main Interface".
remove

Step 3.
Add a new swift file called: main.swift.
main.swift
Add the following code to it, this is require to execute AppDelegate.swift.

Step 4.
Insert the following into

AppDelegate.swift
Enter fullscreen mode Exit fullscreen mode


and comment out

// @NSApplicationMain
Enter fullscreen mode Exit fullscreen mode

Run our app now.
firstrun
Looks good but we need to add a NSViewController to show some content.

Step 5.
Add MyViewController.swift as NSViewController.
myviewcontroller

Connect our new NSWindow with the new MyViewController:

window?.contentViewController = MyViewController()
Enter fullscreen mode Exit fullscreen mode

Color the background of the NSViewController to see if we managed to add to NSWindow.

secondrun

Step 6.
Add some more code to MyViewController.swift to show a label.

thirdrun

There is only one big issue with our new app, there is no Menu as we deleted it with the Main.Storyboard.

Step 7.
Go back to

AppDelegate.swift
Enter fullscreen mode Exit fullscreen mode


and insert the code for menu.

Now, you can quit from menu.

Source code: Github

Sources:

  1. Malik Alayli - Create a macOS app without a Main Storyboard
  2. Christoffer Winterkvist - How to write an NSViewController without interface builder on macOS
  3. Christoffer Winterkvist - How to make a label in macOS
  4. Stackoverflow
  5. Stackoverflow
  6. Stackoverflow
  7. Gene De Lisa - Swift script to create a Cocoa window
  8. Lukas Thoms - AppDelegate is Not The First Code to Run
  9. Stackoverflow

Top comments (1)

Collapse
 
malayli profile image
Malik Alayli

Thank you for referencing my article! :D