Member-only story
How to move to the next TextField SwiftUI?
SwiftUI: Fixing keyboard issues, while creating forms [iOS 14- XCode 12]
In this tutorial, we are going to implement custom TextField. This TextField will have capabilities to pass Keyboard focus. Along with this, we will also enable interactive keyboard dismissal to create better UX for views with multiple TextField like forms.
Let’s divide the problem into smaller subtasks and solve them one by one.
- Wrap UIKit’s UITextField using UIViewRepresentable
- Enable this new TextField to pass keyboard using cross binding
- Add Toolbar for numeric keyboard as they do not have next button inbuild
- Use Introspect to enable interactive keyboard dismissal.
UIKit’s UITextField using UIViewRepresentable:
Create simple UIViewRepresentable with all required parameters like placeholder, text binding, keyboard type.
Set up coordination with TextField delegate. We are going to use these delegates to toggle TextField Focus.
Enable TextField to pass keyboard focus:
To do this, We are going to create a array of bool and a try flag represents active keyboard.
1. on textFieldShouldReturn set next TextField focus true.
2. if textFieldShouldReturn is on last TextField dismiss the keyboard
3. on textFieldDidBeginEditing(user tap of TextField) set all other focus to false and enable focus for current TextField
Code:
///IN Main View
@State var fieldFocus: [Bool] = Array(repeating: false, count: 7)///In Form text field:
var focusable: Binding<[Bool]>? = nilfunc updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
if let focusable = focusable?.wrappedValue {
if focusable[uiView.tag] { ///set focused…