0

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.

Van Du Tran
  • 6,736
  • 11
  • 45
  • 55

1 Answers1

2

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)
    }
}
ScottM
  • 7,108
  • 1
  • 25
  • 42