Type Safely

Share this post
Use @FocusState and @Binding To Control TextField Focus From Any Other View
typesafely.substack.com

Use @FocusState and @Binding To Control TextField Focus From Any Other View

Daily Coding Tip 123

Rob Sturgeon
Jul 3
Share this post
Use @FocusState and @Binding To Control TextField Focus From Any Other View
typesafely.substack.com
Image by Marlene Krohn from Pixabay

@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.

FocusableTextField.swift

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:

FocusableTextFieldContentView.swift

Now I can use a Toggle to control the @FocusState of the TextField, even though it doesn’t exist in the same view.

Last Week’s Daily Coding Tips

  1. Using The Never Type To Deal With Fatal Errors

  2. Use The New UIHostingConfiguration To Display SwiftUI In a UITableViewCell

  3. Use The 'some' Keyword For Any Function Parameter That Conforms To a Protocol

  4. Use The New Type Placeholder Declaration With Underscores

  5. Create a Table Using The New TableColumn In SwiftUI

  6. Use The New NavigationSplitView On iPhone and iPad

Share this post
Use @FocusState and @Binding To Control TextField Focus From Any Other View
typesafely.substack.com
Comments

Create your profile

0 subscriptions will be displayed on your profile (edit)

Skip for now

Only paid subscribers can comment on this post

Already a paid subscriber? Sign in

Check your email

For your security, we need to re-authenticate you.

Click the link we sent to , or click here to sign in.

TopNewCommunity

No posts

Ready for more?

© 2022 Type Safely
Privacy ∙ Terms ∙ Collection notice
Publish on Substack Get the app
Substack is the home for great writing