Member-only story
Mastering SwiftUI’s FocusState
When developing iOS apps using SwiftUI it is critical that focus is managed. That means we gain fine-grained control over which field is in focus at any given time, so long as we are using iOS 15 or later.
Here is an article about @FocusState
, how is it can be used in any apps you might have brewing.
What is @FocusState?
@FocusState
is a property wrapper in SwiftUI that allows developers to manage focus programmatically for input fields like TextField
and SecureField
. By binding the focus state of these components to a shared @FocusState
property, you gain fine-grained control over which field is in focus at any given time.
Essentially FocusState
is an alternative to UIKit’s becomeFirstResponder
and gives similar functionality in a declarative world.
An Example
struct ContentView: View {
@State private var firstName: String = ""
@State private var lastName: String = ""
@FocusState private var focusedField: Field?
enum Field: Hashable {
case firstName
case lastName
}
var body: some View {
Form {
TextField("First Name", text: $firstName)
.focused($focusedField, equals: .firstName)
.submitLabel(.next)
.onSubmit {…