SwiftUI
Updated: September 10, 2025Categories: Languages, Apple, Mobile
Printed from:
SwiftUI Comprehensive Cheatsheet
1. Installation and Setup
Xcode and Swift Requirements
- Xcode 14+ recommended
- Swift 5.7+
- Targets: iOS 16+, macOS 13+, watchOS 9+, tvOS 16+
Project Creation
Swift
123// Create a new SwiftUI project in Xcode
// File > New > Project > App (SwiftUI)
Basic Project Structure
Swift
1234567891011121314151617181920212223242526import SwiftUI
// App entry point
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
// Main view
struct ContentView: View {
var body: some View {
Text("Hello, SwiftUI!")
}
}
// Preview provider
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
2. Basic Views and Controls
Text
Swift
12345Text("Hello, World!")
.font(.title)
.foregroundColor(.blue)
.bold()
Button
Swift
123456789101112131415// Simple button
Button("Click Me") {
// Action
print("Button tapped")
}
// Button with custom styling
Button(action: {
// Action
}) {
Image(systemName: "star.fill")
Text("Favorite")
}
.buttonStyle(.bordered)
Image
Swift
12345678910111213// System image
Image(systemName: "star")
// Local image
Image("myImage")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 100, height: 100)
// Circular image
Image("profile")
.clipShape(Circle())
TextField
Swift
123456@State private var username = ""
TextField("Username", text: $username)
.textFieldStyle(.roundedBorder)
.autocapitalization(.none)
3. Layout and Containers
Stack Views
Swift
123456789101112131415161718// Vertical Stack
VStack(alignment: .leading, spacing: 10) {
Text("First")
Text("Second")
}
// Horizontal Stack
HStack {
Image(systemName: "globe")
Text("Hello")
}
// Depth Stack
ZStack {
Rectangle().fill(Color.blue)
Text("Overlaid Text")
}
LazyVGrid
Swift
1234567891011121314let columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
ScrollView {
LazyVGrid(columns: columns, spacing: 20) {
ForEach(0..<12) { index in
Text("Item \(index)")
}
}
}
4. Modifiers
Styling Modifiers
Swift
1234567Text("Hello")
.font(.headline)
.foregroundColor(.green)
.padding()
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
Layout Modifiers
Swift
12345Rectangle()
.frame(width: 100, height: 100)
.padding()
.border(Color.black)
5. State Management
@State
Swift
12345678910111213struct CounterView: View {
@State private var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
count += 1
}
}
}
}
@Binding
Swift
12345678910111213141516struct ChildView: View {
@Binding var isOn: Bool
var body: some View {
Toggle("Switch", isOn: $isOn)
}
}
struct ParentView: View {
@State private var toggleState = false
var body: some View {
ChildView(isOn: $toggleState)
}
}
@ObservedObject and @StateObject
Swift
123456789101112class UserData: ObservableObject {
@Published var username = ""
}
struct UserProfileView: View {
@StateObject private var userData = UserData()
var body: some View {
TextField("Username", text: $userData.username)
}
}
6. Navigation
NavigationView
Swift
123456789NavigationView {
List(items) { item in
NavigationLink(destination: DetailView(item: item)) {
Text(item.name)
}
}
.navigationTitle("Items")
}
Sheets and Alerts
Swift
1234567891011121314151617struct ContentView: View {
@State private var showSheet = false
@State private var showAlert = false
var body: some View {
Button("Show Sheet") {
showSheet = true
}
.sheet(isPresented: $showSheet) {
DetailView()
}
.alert("Warning", isPresented: $showAlert) {
Button("OK", role: .cancel) {}
}
}
}
7. Lists and Forms
List with ForEach
Swift
123456789101112131415161718struct Item: Identifiable {
let id = UUID()
let name: String
}
struct ListView: View {
let items = [
Item(name: "Apple"),
Item(name: "Banana")
]
var body: some View {
List(items) { item in
Text(item.name)
}
}
}
Form
Swift
123456789101112131415Form {
Section(header: Text("Personal Info")) {
TextField("Name", text: $name)
Picker("Gender", selection: $gender) {
ForEach(genders, id: \.self) { gender in
Text(gender)
}
}
}
Section {
Toggle("Newsletter", isOn: $subscribeNewsletter)
}
}
8. Data Flow
Combine Integration
Swift
12345678class NetworkManager: ObservableObject {
@Published var data: [String] = []
func fetchData() {
// Use Combine for async data fetching
}
}
9. Animations and Transitions
Implicit Animation
Swift
12345678910@State private var scale = 1.0
Circle()
.fill(Color.blue)
.scaleEffect(scale)
.animation(.spring(), value: scale)
.onTapGesture {
scale += 0.5
}
Explicit Animation
Swift
123456Button("Animate") {
withAnimation(.easeInOut(duration: 1)) {
// State changes
}
}
10. Drawing and Graphics
Path and Shape
Swift
1234567891011struct Triangle: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: rect.midX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.closeSubpath()
return path
}
}
11. Gestures
Basic Gestures
Swift
12345678Circle()
.onTapGesture {
// Tap handler
}
.onLongPressGesture {
// Long press handler
}
12. Preview and Testing
PreviewProvider
Swift
12345678910struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewDevice("iPhone 14")
ContentView()
.previewLayout(.sizeThatFits)
}
}
13. UIKit Integration
UIViewRepresentable
Swift
12345678910struct MyUIKitView: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
// Create and return UIView
}
func updateUIView(_ uiView: UIView, context: Context) {
// Update view
}
}
14. Platform-specific Features
Platform Conditionals
Swift
123456#if os(iOS)
// iOS-specific code
#elseif os(macOS)
// macOS-specific code
#endif
15. Common Patterns and Best Practices
- Use
@StateObjectfor view models - Prefer composition over inheritance
- Keep views small and focused
- Use extensions for view modifiers
16. Performance Optimization
- Use
LazyVStackandLazyVGrid - Minimize state updates
- Use
@ViewBuilderfor conditional views
17. Accessibility
Swift
1234Text("Important")
.accessibilityLabel("Accessibility Label")
.accessibilityHint("Accessibility Hint")
18. Debugging Tips
- Use
print()for logging - Leverage Xcode's view debugger
- Check view hierarchy and state
Note: Always refer to the latest Apple documentation for the most up-to-date information.
Continue Learning
Discover more cheatsheets to boost your productivity