What’s New in SwiftUI TextField for iOS 16?
Multi-line text fields, default focus, new autocorrection modifier, text field inside alerts, and fine-tuned scrolling
TextField is one of the core control components for designing UIs with SwiftUI. During WWDC 2020, quite a few handy enhancements were showcased for TextField
. Like:
Multi-line TextFields through the axis parameter
In the next few sections, we’ll be covering them one by one:
Multi-line TextFields
Prior to iOS 16, to build a TextField
that dynamically grows or shrinks with content — we’d either leverage UIViewRepresentable or go the hacky way by using ZStack
.
Gladly, with iOS 16, the axis parameter automatically takes care of that stuff for you.
TextField("Expandable", text: $text, axis: .vertical)
We can further customize and control the TextField
’s dynamic height by using the lineLimit
modifier. Setting a lower and upper range inside lineLimit
lets us set the minimum height of the TextField and the height after which scrolling starts. Like the below TextField has a height that corresponds to 6 lines.
Better Focus Handling Through Default Focus
Earlier, we’d have to resort to asyncAfter
for changing the focus for TextFields. We can do it without any delays now as shown below:
iOS 16 also brings a handy modifier — defaultFocus(_:_:priority:)
to set the default focus programmatically:
A New Modifier for Auto-correction
Auto-correction on TextFields
is enabled by default in SwiftUI. So, passing a boolean in the following modifier made little sense earlier:
//Prior to iOS 16
disableAutocorrection(true)
Now with iOS 16, disableAutocorrection
is deprecated and the new modifier is much easy to plug in and understand:
.autocorrectionDisabled()
Using Text Fields in Alerts
You can now pass TextFields inside the actions
ViewBuilder
argument to create an alert that contains TextField. So, say goodbye to the UIViewRepresentable
way of doing things with iOS 16.
Here’s how to implement TextField inside alerts:
.alert("Title", isPresented:$displayAlert,actions: {
TextField("Email", text: .constant(""), axis: .vertical)
Button ("Save") {}
})
Thanks to Button roles
, we no longer have to rely on the old alert initialiser
that needed primaryButton
and secondaryButton
arguments:
Keyboard Dismissable On Scroll
Not exactly a TextField feature, but the new SwiftUI modifier .scrollDismissesKeyboard(.immediately)
lets you dismiss the keyboard in different ways on a ScrollView. For instance, the mode immediately
causes an immediately dismissal of the keyboard when the scroll is dragged. interactively
dismisses only when the user scrolls up.
scrollDismissesKeyboard
works not only with ScrollView but also with List
and Form
as shown below:
A really handy modifier when building registration forms.
That wraps up the changes in SwiftUI TextField for iOS 16. Thanks for reading.