Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when TextEditor is focused (tapped)

Tags:

swiftui

I have a custom TextField where I detect when the user taps on it to change the look of the field, but I tried to add the same look for the TextEditor, but it doesn't have an onEditingChanged option.

This is my text field:

struct CustomTextField : View {
    @Binding var text : String
    @State private var isEditing = false
    @State var isDisabled = false
    
    init(text : Binding<String>, isDisabled : Bool = false ){
        self._text = text
        self.isDisabled = isDisabled
    }
    
    var body: some View {
        TextField("", text: $text, onEditingChanged: {
            isEditing = $0
        })
        .padding(8)
        .clipShape(RoundedRectangle(cornerRadius: 4))
        .background (
            RoundedRectangle(cornerRadius: 4)
                .stroke(isEditing ? Color("Accent") : Color("Gray"), lineWidth: isDisabled ? 0 : 1)

        )
    }
}

I thought of adding a tap gesture recognizer, but it will only detect when I click, not when I leave the text editor.

Is there a way to detect the focus state of a TextEditor?

like image 632
coopersita Avatar asked Dec 06 '25 08:12

coopersita


1 Answers

Starting with the familiar bad news '@available', you can use the focused modifier, available from iOS 15.

struct ContentView: View {
    
    @State private var text = "Hello focused!"
    @FocusState private var isFocused: Bool
    
    var body: some View {
        TextEditor(text: $text)
            .focused($isFocused)
            .foregroundColor(isFocused ? .red : .black)
    }
}

Note:

  1. This does not work in the canvas preview, run on Simulator.
  2. This is a simple use of FocusState. FocusState has many more options.
like image 130
bauerMusic Avatar answered Dec 08 '25 23:12

bauerMusic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!