Search code examples
swiftuitextfieldtextfieldstyle

How to detect that a TextField is focused when implementing custom TextFieldStyle in SwiftUI


I am implementing a custom TextFieldStyle like follow:

struct CustomTextFieldStyle: TextFieldStyle {
  func _body(configuration: TextField<Self._Label>) -> some View {
    configuration
      .foregroundColor(Color.black)
  }
}

However, I would like to change the foreground color when the text field is "focused". I tried this:

struct CustomTextFieldStyle: TextFieldStyle {

  @Environment(\.isFocused) private var isFocused

  func _body(configuration: TextField<Self._Label>) -> some View {
    configuration
      .foregroundColor(isFocused ? Color.blue : Color.black)
  }
}

but that does not seem to work as isFocused is always false.

Anyone has a hint of how to detect when a textfield is focused? Thanks.


Solution

  • In your text field style, use a @FocusState Boolean, bind that to the text field you’re wrapping and then adjust your formatting based on its value:

    struct CustomTextFieldStyle: TextFieldStyle {
        @FocusState var isFocused: Bool
    
        func _body(configuration: TextField<Self._Label>) -> some View {
            configuration
                .focused($isFocused)
                .foregroundColor(isFocused ? .blue : .black)
        }
    }