-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path10-SynchronizedBindings.swift
64 lines (54 loc) · 1.51 KB
/
10-SynchronizedBindings.swift
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
import SwiftUI
import SwiftUINavigation
private let readMe = """
This demonstrates how to synchronize model state with view state using the "bind" view modifier. \
The model starts focused on the "Username" field, which is immediately focused when the form \
first appears. When you tap the "Sign in" button, the focus will change to the first non-empty \
field.
"""
struct SynchronizedBindings: View {
@FocusState private var focusedField: FeatureModel.Field?
@State private var model = FeatureModel()
var body: some View {
Form {
Section {
Text(readMe)
}
Section {
TextField("Username", text: $model.username)
.focused($focusedField, equals: .username)
SecureField("Password", text: $model.password)
.focused($focusedField, equals: .password)
Button("Sign In") {
model.signInButtonTapped()
}
.buttonStyle(.borderedProminent)
}
.textFieldStyle(.roundedBorder)
}
.bind($model.focusedField, to: $focusedField)
.navigationTitle("Synchronized focus")
}
}
@Observable
private class FeatureModel {
enum Field: String {
case username
case password
}
var focusedField: Field? = .username
var password: String = ""
var username: String = ""
func signInButtonTapped() {
if username.isEmpty {
focusedField = .username
} else if password.isEmpty {
focusedField = .password
} else {
focusedField = nil
}
}
}
#Preview {
SynchronizedBindings()
}