100% found this document useful (2 votes)
324 views

SwiftUI in A Nutshell A Quick Reference Guide For Beginners

The document is a quick reference guide for SwiftUI that introduces common SwiftUI controls and views such as Text, Image, Shape, Toggle, Button, DatePicker, Slider, and more. It provides code examples for building basic views and organizing views using stacks, stacks, and overlays. The guide is intended to help beginners learn SwiftUI.

Uploaded by

rohitpradhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
324 views

SwiftUI in A Nutshell A Quick Reference Guide For Beginners

The document is a quick reference guide for SwiftUI that introduces common SwiftUI controls and views such as Text, Image, Shape, Toggle, Button, DatePicker, Slider, and more. It provides code examples for building basic views and organizing views using stacks, stacks, and overlays. The guide is intended to help beginners learn SwiftUI.

Uploaded by

rohitpradhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Xcode 14.

2 - SwiftUI
Version 1.0.0

SwiftUI
in a
Nutshell
A Quick Reference Guide
for Beginners

by Ishtiak Ahmed
A Quick Reference Guide for Beginners 01

// SwiftUI
// SwiftUI is a modern declarative user interface framework for building iOS,
iPadOS, macOS, watchOS, and tvOS apps using the Swift programming language.

// It provides a simple and intuitive way to create user interfaces with a


live preview, enabling developers to see their changes in real-time.

// SwiftUI also offers a range of built-in user interface controls and


supports dynamic type, and dark mode out of the box.

// In this quick reference guide, we will delve into common SwiftUI


controls..

// APP ENTRY POINT


import SwiftUI

@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
SignInView()
}
}
}

// BASIC VIEW STRUCTURE


struct SignInView: View {
var body: some View {
Text("Sign In")
.font(.title)
}
}

// PRESENT VIEW ON PREVIEW


struct SignInView_Previews: PreviewProvider {
static var previews: some View {
SignInView()
}
}

SwiftUI in a Nutshell by Ishtiak Ahmed


www.ishtiz.com
A Quick Reference Guide for Beginners 02

// TEXT
Text("Welcome")

// ADD SOME STYLES TO THE TEXT


Text("Welcome")
.font(.title) // IMAGE FROM ASSETS
.foregroundColor(.green) Image("avatar1")
.lineLimit(1)

// DATE
Text(Date(), style: .date) // ADD SOME STYLE TO ASSET'S IMAGE
// "February 10, 2023" Image("avatar1")
.resizable()
// TIME .aspectRatio(contentMode: .fit)
Text(Date(), style: .time)
// "7:23 PM” .cornerRadius(2.0)

// LEBEL
// Add icon next to text // IMAGE FROM SF SYMBOLS
Label("SwiftUI in a Nutshell", Image(systemName: "water.waves")
systemImage: "water.waves")

// LEBEL WITH URL


Link("Learn more!”, // ADD SOME STYLES TO SF SYMBOLS IMAGE
destination: URL(string: “https://www.apple.com")!) Image(systemName: "water.waves")
.foregroundColor(.orange)
.font(.title)

// SHAPE

// RECTANGLE SHAPE
Rectangle()
.fill(.orange)
.frame(width: 100, height: 100) // ORGANIZE CHILD VIEWS VERTICALLY
// Put Views inside VStack
VStack {
// CIRCLE SHAPE Text("SwiftUI")
Circle() Text(“in a")
.fill(.orange) Text("Nutshell")
.frame(width: 100, height: 100) }

// ROUNDED RECTANGLE SHAPE // ORGANIZE CHILD VIEWS HORIZONTALLY


RoundedRectangle(cornerRadius: 2) // Put Views inside HStack
HStack {
Text("SwiftUI")
// CAPSULE SHAPE Text(“in a")
Capsule() Text("Nutshell")
.fill(.orange) }

// ELLIPSE SHAPE // ORGANIZE ONE TOP OF ANOTHER


Ellipse() // Put Views inside ZStack
.fill(.orange) ZStack {
Text("SwiftUI in a Nutshell")
RoundedRectangle(cornerRadius: 10)
.frame(width: 100, height: 100)
}

// TOGGLE
// User action for true and false
@State var isActive = true
Toggle(isOn: $isActive) {
Text("FaceID")
}.padding() // TEXT FIELD
// You need a state var to bind
@State var nameText = "Ron"
// BUTTON
Button( TextField($nameText)
action: {
print("Button Tapped!")
}, // ADD SOME STYLES TO THE TEXT FIELD
label: { Text("Add Review") } @State var nameText = ""
)
TextField($nameText)
.textFieldStyle(.roundedBorder)
// IMAGE BUTTON
Button(
action: { // SECURE TEXT FIELD/PASSWORD
print("Play Button Tapped!")
}, @State var password = ""
label: { Image(systemName: "play") } SecureField($password)
)

// TEXT EDITOR
// Supporting multi-line scrollable text input
@State var nameText = ""
TextEditor(text: $nameText)

SwiftUI in a Nutshell by Ishtiak Ahmed


www.ishtiz.com
A Quick Reference Guide for Beginners 03

// DATE PICKER
@State var currentDate = Date()
DatePicker(
$currentDate,
maximumDate: Date(),
displayedComponents: .date // STEPPER WITH DEFAULT INCREMENT
)
@State var progress = 0
// OPTION PICKER Stepper(value: $progress, in: 1...100) {
@State var animalIndex = 1 Text("Progress \(progress)")
Picker("Selected Animal", selection: $animalIndex) { }
ForEach(0 ..< animals.count) { index in
Text(animals[index])
.tag(index) // STEPPER WITH VARIABLE INCREMENT
} Stepper(
}.pickerStyle(.segmented) onIncrement: { progress += 3 },
// SLIDER onDecrement: { progress -= 5 },
@State var downloadProgress = 0 label: {
Slider( Text("Progress \(progress)")
value: $downloadProgress, }
in: 0...100,
onEditingChanged: { editing in )
print(editing)
} // STEPPER WITH VARIABLE INCREMENT
) @State var progress = 0
// PROGRESS Stepper(value: $progress,
ProgressView("Total downloads", value: 13, total: 50) in: 0...100.0,
step: 0.1) {
Text("Progress \(progress)")
}

// IMAGE BACKGROUND
Text("SwiftUI is Cool")
.font(.largeTitle)
.background(
Image(systemName: "play") // LAZY LOAD
.resizable() // LazyVStack
.frame(width: 100, height: 100) // Lazyly load contents in VStack
) ScrollView(.vertical) {
LazyVStack {
// GRADIENT BACKGROUND ForEach(0...1000) { number in
Text("SwiftUI is Cool") Text("Student \(number)")
.background(
LinearGradient( }
gradient: Gradient( }
colors: [.orange,.red,.yellow] }
),
startPoint: .leading, // LazyHStack
endPoint: .trailing // Lazyly load contents in HStack
), ScrollView(.horizontal) {
cornerRadius: 10 LazyHStack {
) ForEach(0...1000) { number in
Text("Student \(number)")

}
}
}

// GRID
// LazyVGrid LazyHGrid
var columns: [GridItem] = Array(
repeating: .init(.flexible(), alignment: .center),
count: 2
) // GESTURE
ScrollView { // TAP GESTURE
LazyVGrid(columns: columns, spacing: 8) { Text("Add")
ForEach(0...1000, id: \.self) { number in .gesture(
Text("Student \(number)") TapGesture()
} .onEnded { _ in
} print(“TAP GESTURE")
} }
)

// TAP GESTURE IN VIEW // DRAG GESTURE


// SINGLE TAP Text("Swipe")
Text("Add") .gesture(
.onTapGesture { DragGesture(minimumDistance: 50)
print("SINGLE TAP") .onEnded { _ in
} print(“DRAG GESTURE")
}
// DOUBLE TAP )
Text("Edit")
.onTapGesture(count: 2) { // LONG PRESS GESTURE
print("DOUBLE TAP") Text("Edit")
} .gesture(
LongPressGesture(minimumDuration: 1)
.onEnded { _ in
print(“LONG PRESS GESTURE")
}
)

SwiftUI in a Nutshell by Ishtiak Ahmed


www.ishtiz.com
A Quick Reference Guide for Beginners 04

// STATIC LIST
List {
// SCROLL VIEW
Text("Account") ScrollView(.horizontal) {
Text("My address")
Text("My orders") Text("White")
}
Text("Blue")
// DYNAMIC LIST
let colors = ["orange", "blue", "red"]
Text("Red")
List(colors, id: \.self) { color in }
Text(color)
}

// LIST WITH SECTION


ScrollView(.vertical) {
List {
Section(header: Text("Theme Colors")) {
Text("White")
Text("Orange") Text("Blue")
Text("Blue")
Text("Red") Text("Red")
}
}
Section(header: Text("Settings")) {
Text("About")
Text("Account")
}
}

// ADD SOME STYLING ON LIST


List {
Section(header: Text("Theme Colors")) { // GROUP
Text("Orange")
Text("Blue") // Group multiple items
Text("Red")
} VStack {
}.listStyle(GroupedListStyle()) Group {
// ADD FOOTER STYLING ON SECTION Text("Orange")
List {
Section(header: Text("Theme Colors"), footer: Text("Blue is default")) { Text("Blue")
Text("Orange")
Text("Blue") Text("Red")
Text("Red")
} }
}.listStyle(GroupedListStyle())
Group {
Text("White")
Text("Black")
}
// FORM }
Form {
Section {
Text("Hello")
Text("World")
} // TAB VIEW
} @State private var selectedTab = 0
TabView(selection: $selectedTab) {
Text("First UI”)
// ADD SPACE .font(.title)
Spacer() .tabItemLabel(Text("First")
.font(.caption))
.tag(0)
// ADD SEPARATOR Text("Second UI")
.font(.title)
Divider() .tabItemLabel(Text("Second")
.font(.caption))
.tag(1)
Text("Third UI")
.font(.title)
.tabItemLabel(Text("Third")
.font(.caption))
// NAVIGATION .tag(2)
NavigationView { }
Text("Dashboard")
.navigationBarTitle(Text("Move"), displayMode: .inline)
}

// ADD A LARGE TITLE


// ADD BAR ITEMS
NavigationView {
Text("Dashboard")
.navigationBarTitle(Text("About"), displayMode: .inline)
.navigationBarItems(
trailing:
Button( // ALERT
action: { print("Move to About") }, Alert(
label: { Text("About") } title: Text("Add to cart"),
) message: Text("Do you want to add?"),
) dismissButton: .default(Text("Ok"))
} )

// NAVIGATE TO OTHER VIEW


NavigationView { // ACTION SHEET
NavigationLink(destination: AnotherView()) { ActionSheet(
Text(“Another View") title: Text("Add to cart"),
}.navigationBarTitle(Text("Dashboard")) message: Text("Do you want to add?"),
} buttons: [
.default(Text("Ok"),
// NAVIGATE THE LIST ITEM action: {
let colors = ["Orange", "Blue", "Red"] print("Decide later")
List(colors, id: \.self) { color in }
NavigationLink(destination: ColorView(colorName: color)) { )
Text(color) ]
} )
}
A Quick Reference Guide for Beginners 05

SwiftUI UIKit
View UIView
Text UILabel
Label with Icon UILabel + ImageView
Link Not Available
Image UIImageView
TextField UITextField
Button UIButton
Toggle UISwitch
Stepper UIStepper
Slider UISlider
Picker UISegmentedControl
TextField UITextField
SecureTextField UITextField
TextEditor UITextView
DatePicker UIDatePicker
ProgressView UIProgressView
Alert UIAlertController
ActionSheet UIAlertController - actionSheet
VStack UIStackView - vertical
LazyVStack Not Available
HStack UIStackView - horizontal
LazyHStack Not Available
LazyVGrid UICollectionView - vertical
LazyHGrid UICollectionView - horizontal
NavigationView UINavigationController
List UITableView
TabView UITabBarController
Map MapKit
Charts Not Available

SwiftUI in a Nutshell by Ishtiak Ahmed


www.ishtiz.com
A Quick Reference Guide for Beginners 06

// SHORTCUTS

QUICK DOCUMENTATION
Option + Click (⌥ Click)

RESUME THE PREVIEW / REFRESH THE PREVIEW


Option + Command + P (⌥ ⌘ P)

TOGGLE SHOW/HIDE THE PREVIEW


Option + Command + return (⌥ ⌘ ↩)

CHANGE SWIFTUI PREVIEW DEVICES/DESTINATION


Control + Shift + 0 (⌃ ⇧ 0)

NAVIGATE TO NEXT/PREVIOUS PREVIEW DESTINATION


Control + Shift + Command + [ (⌃ ⇧ ⌘ [)
Control + Shift + Command + ] (⌃ ⇧ ⌘ ])

OPEN SWIFTUI LIBRARY OF CONTROLS OR MODIFIERS


Shift + Command + L (⇧ ⌘ L)
Shift + Command + [ (⇧ ⌘ [)
Shift + Command + ] (⇧ ⌘ ])

OPEN QUICK ACTIONS MENU OF AN ELEMENT


Command + Click (⌘ Click)

FILE INSPECTOR
Option + Command + 1 (⌥ ⌘ 1)

HISTORY INSPECTOR
Option + Command + 2 (⌥ ⌘ 2)

QUICK HELP INSPECTOR


Option + Command + 3 (⌥ ⌘ 3)

ATTRIBUTES INSPECTOR
Option + Command + 4 (⌥ ⌘ 4)

GET QUICK ACCESS ATTRIBUTE INSPECTOR OF A VIEW


Control + Option + Click (⌃ ⌥ Click)

SwiftUI in a Nutshell by Ishtiak Ahmed


www.ishtiz.com
07

Thanks for Reading


Version 1.0.1 Coming soon

LEGAL
Written and published by Ishtiak Ahmed as eBook & digital, downloadable
format | Copyright © 2023 www.ishtiz.com / Ishtiak Ahmed

All rights reserved. Any unauthorized distribution or reproduction of this


eBook is strictly prohibited without permission from Ishtiak Ahmed except
as permitted by German copyright law(Urheberrechtsgesetz, UrhG).

NEWSLETTER 👉 ishtiz.substack.com
If you have a fondness for free resources such as this guide, you're
welcome to sign up for my newsletter and receive a continuous flow of
curated tips on iOS, Swift, and SwiftUI, along with other free goodies.

Ishtiak Ahmed
Staff iOS Developer based in Munich, 🇩🇪
Website www.ishtiz.com
Twitter @ishtiz_
LinkedIn @ishtiakahmed

NEWSLETTER

You might also like