How to start an iOS app with SceneDelegate without Storyboards
With the introduction of SceneDelegate (which is a great tool), those of us that hate to use storyboards got a couple more hurdles to jump. Instead of just deleting the storyboard and setting the rootViewController on the window in AppDelegate’s didFinishLaunchingWithOptions
, we now have to delete even more references to the StoryBoard, and do our setup in SceneDelegate’s willConnectTo session
.
Not to fear though, once you do it a couple times it becomes second nature. Still waiting for Apple to provide a Storyboard-less template, but assuming that is not going to happen, let’s look at how we can get this done.
First removing the storyboard from all config references
- Start by deleting the Main.storyboard as always.
- Open up your Info.plist
- Delete (-) the row labelled “Main storyboard file base name”
- Go into “Scene Configuration” > “Application Session Role” > “Item 0 (Default Configuration)”
- Delete (-) the row there labelled “Storyboard Name”
Now let’s head over to the SceneDelegate and do it with code. (Yes we use SceneDelegate for window management now, not AppDelegate) Change the existing guard let _ = ...
to guard let windowScene = ...
. This will give us a variable to work with.
Note: SceneDelegate is now used because with the introduction of split screen on many iPhones and iPads, and other features, a user could now have two “Scenes” of your app open at the same time, and you will need to manage those scenes independently of each other. So AppDelegate is for overall app and data setup while SceneDelegate is for individual Scene management.
Now below that, we will do our normal setup, except instead of setting windowBounds, we will set windowScene. Go ahead and create your window
let window = UIWindow(windowScene: windowScene)
Now set the rootViewController
window.rootViewController = ViewController()
Now the makeKeyAndVisisble we all know and love
window.makeKeyAndVisible()
And that’s it! You can head over to your ViewController’s viewDidLoad()
function and give it a view.backgroundColor = .systemPurple
, or something to verify you are seeing the screen you want to.
Note: We use .systemPurple
, instead of .purple
, because apple now defines semantic colors that will transition well on light and dark mode with new iOS features. We should always use semantic colors from here on out.
Go ahead and run in your favorite simulator to verify everything works as it should!
If you would like a full code sample of the two files we edited:
Hope this helped some of you. I’ll probably be back to visit this myself when I forget exactly which references to delete. Till next time…