SwiftUI Fundamentals
49.1 Declarative UI
import SwiftUI
@main
struct TodoApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State private var tasks: [String] = ["Learn Swift", "Build an app"]
@State private var newTask = ""
var body: some View {
NavigationStack {
List {
Section("Add") {
HStack {
TextField("New task", text: $newTask)
.textFieldStyle(.roundedBorder)
Button("Add", systemImage: "plus") {
tasks.append(newTask)
newTask = ""
}
.disabled(newTask.isEmpty)
}
}
Section("Tasks") {
ForEach(tasks, id: \.self) { task in
Label(task, systemImage: "circle")
}
.onDelete { tasks.remove(atOffsets: $0) }
}
}
.navigationTitle("Todos")
.toolbar { EditButton() }
}
}
}
#Preview { ContentView() }49.2 Core Building Blocks
Text and images Text, Image, Label, AsyncImage, SF Symbols
Button, Toggle, Slider, Stepper, Picker, DatePicker, TextField, SecureField, TextEditor, ColorPicker, Menu, ShareLink
VStack, HStack, ZStack, LazyVStack, LazyVGrid, Grid, Spacer, Divider, GeometryReader, ViewThatFits, custom Layout protocol
List, Form, Section, ScrollView, TabView, Group, DisclosureGroup
NavigationStack, NavigationSplitView, NavigationLink, .navigationDestination, .sheet, .fullScreenCover, .popover, .alert, .confirmationDialog, .inspector
.padding, .font, .foregroundStyle, .background, .frame, .cornerRadius/.clipShape, .shadow, .overlay, .opacity, .onTapGesture, .task, .onAppear, .refreshable, .searchable, .animation, .transition Graphics and animation
Shapes, Path, Canvas, gradients, withAnimation, matchedGeometryEffect, PhaseAnimator, KeyframeAnimator, .symbolEffect, Metal shaders (.colorEffect) Swift Charts (Chart { BarMark(...) })
Widgets (WidgetKit), Live Activities, App Intents, visionOS RealityView
49.3 Custom Views and Modifiers
struct CardStyle: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(.background, in: RoundedRectangle(cornerRadius: 12))
.shadow(radius: 4)
}
}
extension View { func cardStyle() -> some View { modifier(CardStyle()) } }
struct ProfileCard: View {
let name: String
var body: some View {
VStack(alignment: .leading) {
Text(name).font(.headline)
Text("Swift Developer").foregroundStyle(.secondary)
}
.cardStyle()
}
}