Member-only story
10 SwiftUI and Swift Coding Tips for Writing Cleaner Code
Write meaningful code and ship your apps faster
1. Set TextField Keyboard Focus in SwiftUI
We’re going to make a custom version of TextField
that can control whether the keyboard is active. In other words, we’re going to control what the first responder is. First, we need a Coordinator
class that will be helpful in responding to events related to UITextView
. Since structures can only conform to protocols and cannot inherit from classes, we are using a class for this:
Now, I have a tendency to use extensions of the provided system types that give me convenience initialisers that simplify their creation.
I’m also including a function for conditionally setting the first responder, as UITextField
uses void methods for both of these and can’t just be sent a boolean value as a parameter:
Finally, we need to create our UIViewRepresentable
. As you can see, the UITextField
is created with our convenience initialiser, which sets the delegate to our CustomTextFieldCoordinator
class. When the UIView
is updated, we make sure that our local bindings are still up to date, including setting the first responder:
To give focus to the keyboard anywhere in your code, simply change the value of the isResponder
binding.