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:

import SwiftUI struct ContentView: View {
  @FocusState private var isFocused: Bool
  var body: some View {
    // Your view code
  }
}

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:

Button("Focus TextField") { isFocused = true }

Here's a complete example of setting TextField focus in SwiftUI:

import SwiftUI struct ContentView: View {
  @State private var yourText: String = ""
  @FocusState private var isFocused: Bool
  
  var body: some View {
    VStack {
      TextField("Enter text here...", text: $yourText)
        .focused($isFocused)
        .padding()
        .border(Color.gray, width: isFocused ? 2 : 1)
        
      Button("Focus TextField") { isFocused = true }
        .padding()
    }
    .padding()
  }
}

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 👨🏻‍💻

Made With Lots of 🔥 by Schurigeln

© 2024 by Christian Konrad

Made With Lots of 🔥 by Schurigeln

© 2024 by Christian Konrad

Made With Lots of 🔥 by Schurigeln

© 2024 by Christian Konrad