How to Get Started with SwiftUI in 5 Minutes

SwiftUI iOS

Posted on 28 Apr 2023 . 5 min read


What is SwiftUI?

SwiftUI is a framework for building user interface for all Apple platforms.


What is the difference between SwiftUI and UIKit?

SwiftUI is a simple and fast way to make user interface but it's quite young and missing lot of features used to make complex apps. On the other hand UIkit is a mature interface builder with lot of existing features.


Should I learn SwiftUI or UIKit in 2023?

SwiftUI is a framework for building user interface for all Apple platforms.


What is the minimum requirement for SwiftUI

  • Xcode 11
  • iOS 13 / macOS 10.15 / tvOS 13 / watchOS 6
  • macOS Catalina


UIKit equivalent in SwiftUI

When we try to make network requests, a console error has been printed.


#View Controller


# UIKit SwiftUI Remarks
1 UIViewController View
2 UITableViewController List
3 UICollectionViewController LazyVGrid and LazyHGrid
4 UISplitViewController NavigationView
5 UINavigationController NavigationView
6 UITabBarController TabView
7 UIPageViewController TabView
8 UIAlertController Alert

#Views and Controls


# UIKit SwiftUI Remarks
1 UILabel Text, Label
2 UITextField TextField
3 UITextView TextEditor
4 UIActivityIndicatorView ProgressView
5 UIImageView Image
6 UIPickerView Picker
7 UIButton Button, Link
8 UIDatePicker DatePicker
9 UIProgressView ProgressView
10 UISegmentedControl Picker
11 UISlider Slider
12 UIStepper Stepper
13 UISwitch Toggle
14 MKMapView Map

#Text

A view that displays one or more lines of text

Text("Hello World")


You can set text as title or caption.

Text("Hello World")
    .font(.title)


You can also apply stylying text as following:

Text("Hello World")
    .bold()
    .italic()


Further more, we can limit line of 1 results in truncation for text.

Text("Hello World")
    .lineLimit(1)


Text alignment

Text("Hello World")
    .multilineTextAlignment(.center)


#Label

A label is a user interface component with combination of image and text.

Label("Lightning", systemImage: "bolt.fill")


You can also set your image.

Label("Weather", image: "weather")


You can set label style to display only icon or only text.

Label("Weather", image: "weather")
    .labelStyle(.titleOnly)


Label("Weather", image: "weather")
    .labelStyle(.iconOnly)


#TextField

A view that displays and can be editable.

@State private var name: String = ""

var body: some View {
    TextField("Name", $name)
}



#SecureField

A control that gives user ability to securely enter private text.

@State private var password: String = ""

var body: some View {
    SecureField("Password", text: $password)
}


#TextEditor

A view that can display and edit multiline, scrollable text.

@State private var fullText: String = ""

var body: some View {
    TextEditor(text: $fullText)
}


#Image

A view that displays an image.


We can use images that stored on the disk, using an Image view.

Image("Tiger")


We can also use images using SF Symbols

Image(systemName: "house.fill")


We can style images as following:

Image("Tiger")
    .resizable() // scales the image to fit the current view
    .aspectRatio(contentMode: .fit)
    .padding(20)
    .frame(width: geometry.size.width/3, height: 65)
    .foregroundColor(Color.orange)


#Button

A control that perform an action.

Button(action: {
    
    }) {
        Text("Cancel")
    }


We can style images as following:

Button(action: {
    
    }) {
        Text("Cancel")
    }
    .font(.headline)
    .foregroundColor(Color.white)
    .background(Color.orange)
    .cornerRadius(20)


#Slider

A control for selecting a value from bounded linear range of value.

@State private var rate = 50.0
@State private var isChanging = false
    Slider(
        value: $rate,
        in: 0...100,
        onEditingChanged: { change in
            isChanging = change
        }
    )


#Stepper

A control that performs increment and decrement actions.

@State private var weight = 0
Stepper {
    Text("Weight: \(weight)")
    } onIncrement: {
        incrementWeight()
    } onDecrement: {
        decrementWeight()
    }


#Toggle

A control that toggles between on and off states.

@State private var isReminderSet = false
Toggle(isOn: $isReminderSet) {
        Text("Reminder is set")
    }


In case of text-only labels:

@State private var isReminderSet = false
Toggle("Reminder is set", isOn: $isReminderSet)


#Picker

A control for selecting from a set of values.

Picker("Pizza", selection: $selectedPizza) {
        Text("Greek Pizza").tag(0)
        Text("Neapolitan Pizza").tag(1)
        Text("Chicago Pizza").tag(2)
    }


Styling pickers

Picker("Pizza", selection: $selectedPizza) {
        Text("Greek Pizza").tag(0)
        Text("Neapolitan Pizza").tag(1)
        Text("Chicago Pizza").tag(2)
    }
    .pickerStyle(.segmented) // segmented or menu


#DatePicker

A control for selecting date.

@State private var date = Date()
DatePicker(
    "Date",
    selection: $date,
    displayedComponents: [.date]
)


Styling date pickers

DatePicker(
    "Date",
    selection: $date,
    displayedComponents: [.date]
)
.datePickerStyle(.graphical)


#ProgressView

A view that shows the progress toward completion of a task.

@State private var progress = 0.5
ProgressView(value: progress)


Styling progress view

ProgressView(value: progress)
    .progressViewStyle(.circular) //linear or circular


#HStack

A view that arranges its subviews in a horizontal line.

HStack(alignment: .top, spacing: 10) {
    Text("Greek Pizza")
    Divider()
    Text("Neapolitan Pizza")
    Divider()
    Text("Chicago Pizza")
}


#LazyHStack

A view that arranges its children in a horizontal line, creating items only as needed.

LazyHStack(alignment: .top, spacing: 10) {
    ForEach(1...50, id: \.self) {
        Text("Column \($0)")
    }
}


#VStack

A view that arranges its subviews in a vertical line.

VStack(alignment: .leading, spacing: 10) {
    Text("Greek Pizza")
    Divider()
    Text("Neapolitan Pizza")
    Divider()
    Text("Chicago Pizza")
}


#LazyVStack

A view that arranges its children in a vertical line, creating items only as needed.

LazyVStack(alignment: .leading) {
    ForEach(1...50, id: \.self) {
        Text("Row \($0)")
    }
}


#ZStack

A view that overlays its subviews in a both axis.

ZStack {
   Image("background")
   Text("Chicago Pizza")
}


#Grid

A container view that displays other views in two dimensional layout.

Grid {
    GridRow {
        Text("Circle")
        Image(systemName: "circle")
    }
    Divider()
    GridRow {
        Image(systemName: "square")
        Text("Square")
    }
}


#Spacer

A view that overlays its subviews in a both axis.

HStack {
   Spacer()
   Image("systemName: "circle")
   Text("Circle")
}


#Divider

A visual element used to seprate from other elements.

VStack {
   Text("Square")
   Divider()
   Text("Circle")
}


#List

A container that presents rows of data in single column.

List {
    Text("Greek Pizza")
    Text("Neapolitan Pizza")
    Text("Chicago Pizza")
}


Add navigation to existing list using NavigationView.

NavigationView {
    List {
        Text("Greek Pizza")
        Text("Neapolitan Pizza")
        Text("Chicago Pizza")
    }
}


Add title and style for list.

NavigationView {
    List {
        Text("Greek Pizza")
        Text("Neapolitan Pizza")
        Text("Chicago Pizza")
    }.listStyle(.grouped)
}.navigationTitle("Pizza")


#ScrollView

A view that displays its content in scrollable view.

ScrollView {
        VStack(alignment: .leading) {
            ForEach(0..<50) {
                Text("Number \($0)")
            }
        }
}


Conclusion

Overall, SwiftUI is a powerful and user-friendly framework that is well-suited for building modern and engaging user interfaces on Apple platforms. While it may take some time to learn, the benefits of using SwiftUI can be significant in terms of productivity, performance, and user satisfaction.


Don’t hesitate to contact me if you have any questions or queries. Follow me on twitter @gurjitpt for any updates.

Thanks!


Share this article


Generic placeholder image

WRITTEN BY

Gurjit Singh

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me on twitter @gurjitpt for more updates.

Related Articles


Deep Dive into Autorelease Pools in Swift

In the realm of software development, memory management plays a crucial role in ensuring the efficient allocation and deallocation of memory...

2024-01-28 . 4 min read     Swift Autorelease

Read More »

Swift enum equatable: with or without associated values

Swift enums provide a powerful way to model a set of related values. Enums can be equipped with associated values, allowing them to represen...

2024-01-24 . 3 min read     Swift Enums

Read More »

How to create Date Picker in SwiftUI

Use a DatePicker when creating a view that enables users to choose both a calendar date and, if needed, a specific time.In SwiftUI, you can ...

2024-01-16 . 2 min read     SwiftUI DatePicker

Read More »

Getting started with Swiftlint to enforce Swift style

SwiftLint is a tool that ensures Swift code adheres to defined style guidelines. It automates code review by identifying and suggesting impr...

2023-12-29 . 4 min read     Swift SwiftLint

Read More »

How to use Lottie animation in SwiftUI

Lottie is a fantastic tool for incorporating high-quality animations into your SwiftUI projects. There are several ways to add Lottie to pro...

2023-12-13 . 2 min read     SwiftUI Lottie

Read More »

How to get index in Foreach in SwiftUI

In SwiftUI, the ForEach is used to iterate over a collection of data and create views dynamically based on that data....

2023-12-07 . 3 min read     SwiftUI ForEach

Read More »