0

I am trying to put an overlay on a text field when it is the active first responder in the current scene.

TextField("", text: valueProxy, onEditingChanged: { self.isEditing = $0 })
                    .padding(EdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8))
                    .overlay(RoundedRectangle(cornerRadius: 2).stroke(Color.accentColor, lineWidth: self.isEditing ? 1: 0))

This works well when all the fields on the form are text fields, but it stops working when a toggle control or some other field is tapped.

In those cases onEditingChanged does not appear to be called at all, so I could end up with potentially having multiple fields that look like they have focus.

NOTE: The closest I got was to dismiss the keyboard upon tap occurring elsewhere, based on the question below

How to hide keyboard when using SwiftUI?

But even that has limitations when certain views are configured to appear/disappear upon gestures other than onTap.

I think a safer approach would be to check for first responder status and bind any custom highlighting to that variable. Does anyone have a method that can expose if a view is indeed the first responder?

Nish
  • 51
  • 1
  • 7

1 Answers1

0

a couple of things. the easiest way to dismiss keyboard upon tab is to use this library, https://github.com/hackiftekhar/IQKeyboardManager. theres an issue that talks about how to use it in swiftUI, https://github.com/hackiftekhar/IQKeyboardManager/issues/1606.

As for finding the responder status, i use another library called Introspect, https://github.com/siteline/SwiftUI-Introspect. with it you can do this:

TextField("", text: valueProxy)
  .introspectTextField { textField in self.isEditing = textField.isFirstResponder }
                    .padding(EdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8))
                    .overlay(RoundedRectangle(cornerRadius: 2).stroke(Color.accentColor, lineWidth: self.isEditing ? 1: 0))```
BokuWaTaka
  • 168
  • 6