By the end of this lesson, you will understand what SwiftUI is, its advantages, and how it differs from UIKit. You will also create your first SwiftUI project and get familiar with its basic structure and lifecycle.
SwiftUI is Appleās modern framework for building user interfaces across all Apple platforms using a declarative Swift syntax.
SwiftUI uses a declarative style, whereas UIKit uses an imperative style. Here is a comparison:
UIKit Example:
let label = UILabel()
label.text = "Hello, World!"
view.addSubview(label)
SwiftUI Example:
Text("Hello, World!")
Explanation:
Follow these steps to create a SwiftUI project:
The initial project structure includes ContentView.swift
and YourAppApp.swift
.
ContentView Structure:
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
This code creates a simple view displaying "Hello, World!" with padding around it.
Explanation:
struct ContentView: View
: Defines a new view called ContentView
that conforms to the View
protocol.var body: some View
: The body property describes the view's content and layout.Text("Hello, World!")
: Displays a text view with the string "Hello, World!"..padding()
: Adds padding around the text view.struct ContentView_Previews: PreviewProvider
: Provides a live preview of the view in Xcode's canvas.Let's create a more detailed example:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, World!")
.padding()
Text("Welcome to SwiftUI")
.font(.headline)
.foregroundColor(.blue)
Spacer()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Explanation:
VStack { ... }
: A vertical stack that arranges its children vertically. This is useful for creating column-like layouts.Spacer()
: Adds flexible space to push the views to the top. This is useful for creating layouts that adapt to different screen sizes..font(.headline)
: Sets the font style to headline, making the text appear larger and bolder..foregroundColor(.blue)
: Sets the text color to blue. You can use various predefined colors or create custom ones.