Use @FocusState and @Binding To Control TextField Focus From Any Other View
Daily Coding Tip 123

@FocusState
is an interesting property wrapper that works differently to @State
and @Binding
. Setting the value of a Boolean @FocusState
called focused
to true has no effect unless a TextField
has a .focused($focused)
modifier. Since it doesn’t work as a Binding
, we can’t control this property from elsewhere. I came up with a somewhat hacky workaround for this, but it makes @FocusState
a lot more useful in my opinion.
Yes, I’m using an onChange
modifier to change the local @FocusState
according to an external @Binding
.
When I want to use it elsewhere, I simply pass a Binding
to the initialiser of FocusableTextField
:
Now I can use a Toggle
to control the @FocusState
of the TextField
, even though it doesn’t exist in the same view.