Skip to content

Instantly share code, notes, and snippets.

@DrBeta
Last active December 17, 2019 00:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrBeta/0cf5a41d6d0b77bda3d9b4a6de8cdf9b to your computer and use it in GitHub Desktop.
Save DrBeta/0cf5a41d6d0b77bda3d9b4a6de8cdf9b to your computer and use it in GitHub Desktop.
Programmatic layout in iOS 13

You sometimes need to have a programmatic layout when making iOS apps. But, if you have been playing around with the Xcode beta, you might notice that your old code to do that doesn't work. This code is used in the func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) in SceneDelegate.swift to initialize the programmatic layout. There is also a Storyboard name in the Info.plist you have to delete. Happy coding!

//Stuff before here (not neccesary for this gist)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else {
fatalError("Could not cast scene to UIWindowScene.")
}
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIViewController()
self.window = window
window.makeKeyAndVisible()
}
//Stuff after here (not neccesary for this gist)
@vermont42
Copy link

vermont42 commented Nov 9, 2019

Thanks for sharing this! I modified slightly to reflect the fact that operation can't continue in the unlikely event that the windowScene cast fails.

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = scene as? UIWindowScene else {
      fatalError("Could not cast scene to UIWindowScene.")
    }
    let window = UIWindow(windowScene: windowScene)
    window.rootViewController = UIViewController()
    self.window = window
    window.makeKeyAndVisible()
  }

I like the fail-early approach because it documents my expectations of behavior, and the decreased indentation helps readability.

If you're interested in my approach to programmatic layout, here is a whole tutorial: https://racecondition.software/blog/programmatic-layout/

I need to update the tutorial with a variant of your gist.

@DrBeta
Copy link
Author

DrBeta commented Dec 17, 2019

Updated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment