SwiftUI Getting Started Tutorial

At WWDC19 Apple introduces SwiftUI, which is a native declarative UI framework. SwiftUI let developers declare what they want to put in the UI and SwiftUI makes sure all rules are enforced. SwiftUI is also cross-platform that works across iOS, macOS, tvOS and watchOS. In this tutorial a basic SwiftUI project will be created to show the fundamentals of SwiftUI. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIGettingStartedTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

The basic Single View App template includes the SceneDelegate.swift file. In the Project navigator, click to select SceneDelegate.swift. The following lines of code creates a new ContentView instance which is visible at startup.

let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()

In the Project navigator, click to select ContentView.swift. The ContentView structure describes the view’s content and layout.

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}

The ContentView_Preview struct declares a preview for that view.

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

The preview will display the Hello World text, now change the text view in the Editor.

Text("Hello ioscreator")

As the code is changed, the preview updates to reflect the changes.

It is also possible to change the code by using the inspector. Command-click the Text in the preview and choose Inspect.

Change the Font modifier to Large Title. This applies the system font to the text.

The Font modifier is also applied to the Text view in the Editor.

Text("Hello ioscreator")
    .font(.largeTitle)

Modifiers can be used to customize a SwiftUI view. In the Edtor Add the .foregroundColor(.red) modifier.

struct ContentView : View {
    var body: some View {
        Text("Hello ioscreator")
            .font(.largeTitle)
            .foregroundColor(.red)
    }
}

This changes the text's color to red in the preview.

The source code of the SwiftUIGettingStartedTutorial can be downloaded at the ioscreator repository on Github.