Discussion
議論
Use this modifier to cause the view to receive focus whenever the the binding
equals the value
. Typically, you create an enumeration of fields that may receive focus, bind an instance of this enumeration, and assign its cases to focusable views.
The following example uses the cases of a LoginForm
enumeration to bind the focus state of two TextField
views. A sign-in button validates the fields and sets the bound focusedField
value to any field that requires the user to correct a problem.
struct LoginForm {
enum Field: Hashable {
case usernameField
case passwordField
}
@State private var username = ""
@State private var password = ""
@FocusState private var focusedField: Field?
var body: some View {
Form {
TextField("Username", text: $username)
.focused($focusedField, equals: .usernameField)
SecureField("Password", text: $password)
.focused($focusedField, equals: .passwordField)
Button("Sign In") {
if username.isEmpty {
focusedField = .usernameField
} else if password.isEmpty {
focusedField = .passwordField
} else {
handleLogin(username, password)
}
}
}
}
}
To control focus using a Boolean, use the focused(_:)
method instead.