Setting a Text Field's Focus on Launch #4
diegolavalledev
announced in
Posts
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Originally published on diegolavalle.com.
Like so many of us I was waiting for better focus control on SwiftUI. It finally came in the form of the FocusState property wrapper which let's us bind a property to an element's focus state.
Let's say we have a form like this one, with one text field and a button.
We would like to control the focus of the text field by pressing the button. For this we need a boolean property wrapped with
@FocusState
which we will bind to the field using the focused view modifier.We can now use the button to toggle the focus state of the text field.
But what if we want to set the focus on the text field at launch. This seems to be the default behavior on macOS but not on iOS.
In the pass we would have probably attempted to do something with
onAppear(perform:)
but new in iOS 15 is the task modifier which taps into Swift's new concurrency capabilities. Unfortunately what should be rather straightforward is not really working as of Xcode 13.1. Bummer.But not all is lost. Previously we could have attempted the old trick of calling
asyncAfter
on the main dispatch queue and introduce an artificial delay. Today with async/await we can apply the equally nasty hack with a little more conciseness usingTask.sleep
.That code achieves what we want although the hard-coded nanosecond value leaves the question whether this threshold will always be the same regardless of device and runtime conditions.
For now the final solution just works and our little test form is complete.
Are there better solutions to work around what seems to be a bug on Apple's side? Leave a comment in the discussion area and tell me what you think.
Beta Was this translation helpful? Give feedback.
All reactions