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?
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:
FocusState. FocusState has many more options.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With