< How to position views in a grid using LazyVGrid and LazyHGrid | How to hide the scroll indicators in ScrollView, List, and more > |
Updated for Xcode 14.2
New in iOS 16
SwiftUI’s scrollDismissesKeyboard()
modifier gives us precise control over how the keyboard should dismiss when the user scrolls around.
For example, we could place a TextField
and TextEditor
into a scroll view, and have them both dismiss the keyboard interactively like this:
struct ContentView: View {
@State private var username = "Anonymous"
@State private var bio = ""
var body: some View {
ScrollView {
VStack {
TextField("Name", text: $username)
.textFieldStyle(.roundedBorder)
TextEditor(text: $bio)
.frame(height: 400)
.border(.quaternary, width: 1)
}
.padding(.horizontal)
}
.scrollDismissesKeyboard(.interactively)
}
}
Download this as an Xcode project
The scrollDismissesKeyboard()
modifier can be given one of four values, all of which are useful in their own way:
.automatic
to let SwiftUI judge what’s the best thing to do based on the context of the scroll..immediately
to make the keyboard dismiss fully as soon as any scroll happens..interactively
to make the keyboard dismiss inline with the user’s gesture – they need to scroll further to make it dismiss fully..never
if you want the keyboard to remain present during scrolling.According to Apple’s documentation, text editors should use interactive dismissal by default, whereas other views should use immediate, but that certainly doesn’t seem to be the case right now.
SPONSORED Build a functional Twitter clone using APIs and SwiftUI with Stream's 7-part tutorial series. In just four days, learn how to create your own Twitter using Stream Chat, Algolia, 100ms, Mux, and RevenueCat.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.