SwiftUI is a great way to build apps. It’s simple, concise, and fast. What’s made in UIKit can be recreated in SwiftUI with half the lines of code. What used to take weeks now only takes hours. But until today, it had a serious drawback: It depended on UIKit.
To display a view made with SwiftUI, you had to wrap it in a UIHostingController
, which had to be wrapped in a UIWindow
, which had to be defined in SceneDelegate
:
import UIKit
import SwiftUI
// Auto-generated code
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
...
}
For a framework designed for simplicity and performance… all that code doesn’t make sense. Why write 30 lines of code just to define a view?!
Today, at WWDC20, a solution was announced: App
.
Huh, App
? Yes, App
. The App
protocol. It’s so simple it sounds weird after saying it a few times.
In Xcode 11.5 up to Xcode 12 beta, you’ll see a new option when creating a SwiftUI app: “SwiftUI App.”
What, is Apple trying to add an echo generator to Xcode? Not really — it’s actually one of the two options for “Life Cycle”:
“Life Cycle” refers to the application’s state — usually along the lines of “active,” “inactive,” or “background.” We use this to display the UI on launch as well as save user data on exit.
Previously, this was handled in AppDelegate
and SceneDelegate
, making it a hassle to manage application state — it was spread out across two files! Two. Files. Preposterous!
Well, if you select “SwiftUI App” and create the project, you’ll notice that both AppDelegate
and SceneDelegate
are gone! Instead, a file called <App Name>App
replaces them!
#swiftui #mobile #programming #swift #ios #mobile app