Build declarative UIs with SwiftUI views, modifiers, @State, @Binding, and @ObservedObject.
SwiftUI Basics
# Requires Xcode 15+ and iOS 17+ for latest features
# iOS deployment target: 16.0+View Protocol
import SwiftUI
// Every SwiftUI view conforms to View protocol
struct ContentView: View {
// body is the only required property
var body: some View {
Text("Hello, SwiftUI!")
.font(.title)
.foregroundColor(.blue)
}
}
// Preview provider
#Preview {
ContentView()
}Basic Views
struct BasicViews: View {
var body: some View {
VStack(spacing: 20) {
// Text
Text("Title")
.font(.largeTitle)
.bold()
Text("Subtitle with **markdown** support")
.font(.subheadline)
.foregroundStyle(.secondary)
// Image
Image(systemName: "swift")
.font(.system(size: 60))
.foregroundColor(.orange)
Image("custom-image") // From asset catalog
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 100)
// Shape
Circle()
.fill(Color.blue.gradient)
.frame(width: 100, height: 100)
RoundedRectangle(cornerRadius: 20)
.stroke(Color.red, lineWidth: 4)
.frame(width: 150, height: 80)
}
}
}Layout Containers
struct LayoutViews: View {
var body: some View {
VStack(spacing: 30) {
// VStack - vertical
VStack(alignment: .leading, spacing: 10) {
Text("First")
Text("Second")
Text("Third")
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.gray.opacity(0.1))
// HStack - horizontal
HStack(spacing: 15) {
Image(systemName: "star.fill").foregroundColor(.yellow)
Text("Horizontal")
Spacer() // Pushes content apart
Text("Layout")
}
// ZStack - overlay
ZStack {
RoundedRectangle(cornerRadius: 20)
.fill(Color.blue.gradient)
Text("On Top")
.font(.title)
.foregroundColor(.white)
}
.frame(height: 100)
// Lazy stacks (scrollable)
ScrollView {
LazyVStack(spacing: 10) {
ForEach(1...20, id: \.self) { i in
Text("Row \(i)")
.frame(maxWidth: .infinity)
.padding()
.background(Color.gray.opacity(0.1))
}
}
.padding()
}
.frame(height: 200)
// Grid
ScrollView {
LazyVGrid(columns: [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
], spacing: 10) {
ForEach(1...12, id: \.self) { i in
RoundedRectangle(cornerRadius: 10)
.fill(Color.blue.opacity(0.3))
.frame(height: 80)
.overlay(Text("\(i)"))
}
}
.padding()
}
.frame(height: 200)
}
.padding()
}
}State Management
// @State - local view state (value type)
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 20) {
Text("Count: \(count)")
.font(.largeTitle)
HStack(spacing: 20) {
Button("Decrement") { count -= 1 }
.buttonStyle(.borderedProminent)
Button("Increment") { count += 1 }
.buttonStyle(.borderedProminent)
}
Button("Reset") { count = 0 }
.buttonStyle(.bordered)
}
}
}
// @Binding - two-way binding to parent state
struct ChildView: View {
@Binding var name: String
var body: some View {
TextField("Enter name", text: $name)
.textFieldStyle(.roundedBorder)
.padding()
}
}
struct ParentView: View {
@State private var userName = ""
var body: some View {
VStack {
Text("Hello, \(userName.isEmpty ? "World" : userName)!")
ChildView(name: $userName) // Pass binding with $
}
.padding()
}
}
// @Observable (iOS 17+) - reference type observation
@Observable
class UserViewModel {
var name = ""
var email = ""
var isLoading = false
var error: String?
func save() async {
isLoading = true
defer { isLoading = false }
// Save logic
}
}
struct ObservableView: View {
@State private var viewModel = UserViewModel()
var body: some View {
Form {
TextField("Name", text: $viewModel.name)
TextField("Email", text: $viewModel.email)
if viewModel.isLoading {
ProgressView()
} else {
Button("Save") {
Task { await viewModel.save() }
}
}
if let error = viewModel.error {
Text(error).foregroundColor(.red)
}
}
}
}
// @Environment - global values
struct EnvironmentView: View {
@Environment(\.colorScheme) var colorScheme
@Environment(\.horizontalSizeClass) var sizeClass
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
Text("Color scheme: \(colorScheme == .dark ? "Dark" : "Light")")
Text("Size class: \(sizeClass == .compact ? "Compact" : "Regular")")
Button("Dismiss") { dismiss() }
}
}
}
// @EnvironmentObject - shared observable object (legacy)
class AppSettings: ObservableObject {
@Published var theme: ColorScheme = .light
@Published var fontSize: CGFloat = 16
}
struct SettingsView: View {
@EnvironmentObject var settings: AppSettings
var body: some View {
Toggle("Dark Mode", isOn: Binding(
get: { settings.theme == .dark },
set: { settings.theme = $0 ? .dark : .light }
))
}
}Modifiers
struct ModifierExamples: View {
var body: some View {
Text("Modified Text")
// Order matters!
.font(.title)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)
.shadow(radius: 5)
.padding() // Outer padding
// Conditional modifiers
Text("Conditional")
.font(.title)
.foregroundColor(.primary)
.if(true) { view in
view.bold()
}
.if(false) { view in
view.italic()
}
// Animation
@State var isExpanded = false
Circle()
.fill(isExpanded ? .red : .blue)
.frame(width: isExpanded ? 100 : 50, height: isExpanded ? 100 : 50)
.animation(.spring(), value: isExpanded)
.onTapGesture { isExpanded.toggle() }
}
}
// Helper for conditional modifiers
extension View {
@ViewBuilder
func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
if condition { transform(self) } else { self }
}
}Lists & Navigation
struct Item: Identifiable {
let id = UUID()
let title: String
let subtitle: String
}
struct ListView: View {
let items = [
Item(title: "SwiftUI", subtitle: "Declarative UI"),
Item(title: "Combine", subtitle: "Reactive programming"),
Item(title: "Core Data", subtitle: "Persistence"),
]
var body: some View {
NavigationStack {
List(items) { item in
NavigationLink(item.title) {
DetailView(item: item)
}
}
.navigationTitle("Topics")
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button("Add") { }
}
}
}
}
}
struct DetailView: View {
let item: Item
var body: some View {
VStack(spacing: 20) {
Text(item.title).font(.largeTitle)
Text(item.subtitle).font(.body).foregroundStyle(.secondary)
Spacer()
}
.padding()
.navigationTitle(item.title)
.navigationBarTitleDisplayMode(.inline)
}
}Forms & Controls
struct FormView: View {
@State private var name = ""
@State private var email = ""
@State private var notifications = true
@State private var volume = 0.5
@State private var selection = 0
@State private var date = Date()
@State private var color = Color.blue
var body: some View {
NavigationStack {
Form {
Section("Profile") {
TextField("Name", text: $name)
TextField("Email", text: $email)
.keyboardType(.emailAddress)
.autocapitalization(.none)
}
Section("Preferences") {
Toggle("Notifications", isOn: $notifications)
Picker("Theme", selection: $selection) {
Text("Light").tag(0)
Text("Dark").tag(1)
Text("System").tag(2)
}
Slider(value: $volume, in: 0...1) {
Text("Volume")
} minimumValueLabel: {
Image(systemName: "speaker.fill")
} maximumValueLabel: {
Image(systemName: "speaker.wave.3.fill")
}
DatePicker("Birthday", selection: $date, displayedComponents: .date)
ColorPicker("Accent Color", selection: $color)
}
Section {
Button("Save", action: {})
.frame(maxWidth: .infinity)
.buttonStyle(.borderedProminent)
}
}
.navigationTitle("Settings")
}
}
}Custom Components
// Reusable button style
struct PrimaryButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.headline)
.foregroundColor(.white)
.frame(maxWidth: .infinity)
.padding()
.background(Color.blue)
.cornerRadius(12)
.scaleEffect(configuration.isPressed ? 0.98 : 1)
.animation(.easeInOut(duration: 0.1), value: configuration.isPressed)
}
}
// Reusable card view
struct Card<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
content
.padding()
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 16))
.shadow(radius: 2)
}
}
// Usage
struct ComponentView: View {
var body: some View {
VStack(spacing: 20) {
Button("Primary Action") { }
.buttonStyle(PrimaryButtonStyle())
Card {
VStack(alignment: .leading) {
Text("Card Title").font(.headline)
Text("Card content goes here")
}
}
}
.padding()
}
}Animation
struct AnimationView: View {
@State private var isRotated = false
@State private var scale = 1.0
@State private var offset = CGSize.zero
var body: some View {
VStack(spacing: 30) {
// Implicit animation
RoundedRectangle(cornerRadius: 20)
.fill(.blue.gradient)
.frame(width: 100, height: 100)
.rotationEffect(.degrees(isRotated ? 360 : 0))
.scaleEffect(scale)
.offset(offset)
.animation(.spring(response: 0.5, dampingFraction: 0.6), value: isRotated)
.animation(.spring(), value: scale)
.animation(.interactiveSpring(), value: offset)
HStack(spacing: 20) {
Button("Rotate") { isRotated.toggle() }
Button("Scale") { scale = scale == 1 ? 1.5 : 1 }
Button("Move") { offset = offset == .zero ? CGSize(width: 50, height: 0) : .zero }
}
.buttonStyle(.borderedProminent)
// Explicit animation
Button("Animate All") {
withAnimation(.spring()) {
isRotated.toggle()
scale = scale == 1 ? 1.5 : 1
offset = offset == .zero ? CGSize(width: 50, height: 0) : .zero
}
}
.buttonStyle(.bordered)
}
}
}
// Matched geometry effect (hero transitions)
struct HeroView: View {
@Namespace private var namespace
@State private var selected: Int?
var body: some View {
VStack {
if let selected = selected {
DetailView(item: selected, namespace: namespace)
} else {
ListView(selected: $selected, namespace: namespace)
}
}
}
}Try It
Create a new SwiftUI project. Build a counter with @State. Create a form with @Binding. Make a custom ButtonStyle. Animate a view.
# Xcode → File → New → Project → iOS → App
# Select SwiftUI interfaceBuild SwiftUI interfaces
- Create a todo list with add/delete/swipe actions
- Build a settings screen with Form and @AppStorage
- Make a custom TabView with animated selection
- Implement pull-to-refresh on a List
- Create a card flip animation with matchedGeometryEffect
- Build a onboarding flow with TabView and PageTabViewStyle
SwiftUI is declarative: describe what UI should look like for each state. State drives UI. Use @State for local, @Binding for two-way, @Observable for shared reference types. Modifiers chain - order matters. Prefer value types (structs) for views.
Resources
- SwiftUI Tutorials: https://developer.apple.com/tutorials/swiftui
- SwiftUI Documentation: https://developer.apple.com/documentation/swiftui
- WWDC SwiftUI Sessions: https://developer.apple.com/videos/wwdc2023/
- SwiftUI Lab: https://swiftui-lab.com/