Set TextField Focus in SwiftUI
Managing the focus of a TextField in SwiftUI has been a long-awaited feature, as it allows developers to create more user-friendly and intuitive interfaces. With the introduction of the @FocusState
property wrapper and the focused
modifier in SwiftUI 3 (iOS 15, macOS 12), developers can now easily control the focus state of their TextFields. In this blog post, we will explore how to set TextField focus in SwiftUI using these new tools.
First, you need to create a @FocusState
property in your view to keep track of the TextField's focus status. The FocusState
property should be of the FocusState<Bool>.Binding
type. Here's an example:
Next, add a TextField to your view and use the focused
modifier to bind the TextField's focus state to the @FocusState
property created earlier:
TextField("Enter text here...", text: $yourText) .focused($isFocused)
Now that the focus state is connected to the TextField, you can control the focus programmatically using the isFocused
property. For example, you can create a button that focuses the TextField when tapped:
Here's a complete example of setting TextField focus in SwiftUI:
In this example, we have a TextField with a focus state managed by the isFocused
property. The TextField's border color changes based on its focus state. There's also a button that, when tapped, sets the focus state to true, thus focusing the TextField.
Hope that article helps you focus on the things that matter.
XOXO,
Christian 👨🏻💻