-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwiftPlaybook.txt
265 lines (211 loc) · 5.18 KB
/
SwiftPlaybook.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# SwiftUI Coding Solutions Playbook
Author: Anthropic's AI Claude
This playbook covers some of the most common SwiftUI patterns and solutions.
## Table of Contents
1. Structs
2. Classes
3. Functions
4. Views
5. State and Binding
6. ObservableObject
7. Environment Objects
8. View Modifiers
9. Lists and Navigation
10. Gestures
## 1. Structs
Structs are value types and are commonly used in SwiftUI for model data.
```swift
struct User {
let id: UUID
var name: String
var age: Int
}
// Usage
let user = User(id: UUID(), name: "John Doe", age: 30)
```
## 2. Classes
Classes are reference types and are used when you need inheritance or reference semantics.
```swift
class UserManager {
static let shared = UserManager()
private init() {}
var currentUser: User?
func login(user: User) {
currentUser = user
}
func logout() {
currentUser = nil
}
}
```
## 3. Functions
Functions in Swift can be standalone or part of a type.
```swift
func greet(_ name: String) -> String {
return "Hello, \(name)!"
}
// Usage
let greeting = greet("Alice")
```
## 4. Views
Views are the building blocks of your SwiftUI interface.
```swift
struct ContentView: View {
var body: some View {
VStack {
Text("Welcome to SwiftUI")
.font(.title)
Button("Tap me") {
print("Button tapped")
}
}
}
}
```
## 5. State and Binding
`@State` is used for local state, while `@Binding` allows you to pass mutable state to child views.
```swift
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
count += 1
}
CounterButtonView(count: $count)
}
}
}
struct CounterButtonView: View {
@Binding var count: Int
var body: some View {
Button("Decrement") {
count -= 1
}
}
}
```
## 6. ObservableObject
`ObservableObject` is used for more complex state management across multiple views.
```swift
class UserViewModel: ObservableObject {
@Published var user: User?
func fetchUser() {
// Simulating an API call
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.user = User(id: UUID(), name: "Jane Doe", age: 28)
}
}
}
struct UserView: View {
@StateObject private var viewModel = UserViewModel()
var body: some View {
VStack {
if let user = viewModel.user {
Text("Name: \(user.name)")
Text("Age: \(user.age)")
} else {
Text("Loading...")
}
}
.onAppear {
viewModel.fetchUser()
}
}
}
```
## 7. Environment Objects
Environment objects allow you to share data throughout your app's view hierarchy.
```swift
class AppSettings: ObservableObject {
@Published var isDarkMode = false
}
@main
struct MyApp: App {
@StateObject private var appSettings = AppSettings()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(appSettings)
}
}
}
struct ContentView: View {
@EnvironmentObject var appSettings: AppSettings
var body: some View {
Toggle("Dark Mode", isOn: $appSettings.isDarkMode)
}
}
```
## 8. View Modifiers
Custom view modifiers allow you to encapsulate common view modifications.
```swift
struct RoundedBackground: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(Color.blue)
.cornerRadius(10)
}
}
extension View {
func roundedBackground() -> some View {
self.modifier(RoundedBackground())
}
}
// Usage
Text("Hello, World!")
.roundedBackground()
```
## 9. Lists and Navigation
SwiftUI makes it easy to create lists and navigation hierarchies.
```swift
struct Item: Identifiable {
let id = UUID()
let name: String
}
struct ListView: View {
let items = [Item(name: "Apple"), Item(name: "Banana"), Item(name: "Cherry")]
var body: some View {
NavigationView {
List(items) { item in
NavigationLink(destination: DetailView(item: item)) {
Text(item.name)
}
}
.navigationTitle("Fruits")
}
}
}
struct DetailView: View {
let item: Item
var body: some View {
Text("Details for \(item.name)")
}
}
```
## 10. Gestures
SwiftUI provides a declarative way to handle gestures.
```swift
struct GestureView: View {
@State private var offset = CGSize.zero
var body: some View {
Circle()
.fill(Color.blue)
.frame(width: 100, height: 100)
.offset(offset)
.gesture(
DragGesture()
.onChanged { gesture in
offset = gesture.translation
}
.onEnded { _ in
withAnimation {
offset = .zero
}
}
)
}
}
```