How to dismiss the keyboard when the user scrolls
About 2 min
How to dismiss the keyboard when the user scrolls 관련
SwiftUI by Example
Back to Home
How to dismiss the keyboard when the user scrolls | SwiftUI by Example
How to dismiss the keyboard when the user scrolls
Updated for Xcode 15
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)
}
}
The scrollDismissesKeyboard()
modifier can be given one of four values, all of which are useful in their own way:
- Use
.automatic
to let SwiftUI judge what's the best thing to do based on the context of the scroll. - Use
.immediately
to make the keyboard dismiss fully as soon as any scroll happens. - Use
.interactively
to make the keyboard dismiss inline with the user's gesture – they need to scroll further to make it dismiss fully. - Use
.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.
Similar solutions…
How to dismiss the keyboard for a TextField | SwiftUI by Example
How to dismiss the keyboard for a TextField
How to make a view dismiss itself | SwiftUI by Example
How to make a view dismiss itself
How to add a toolbar to the keyboard | SwiftUI by Example
How to add a toolbar to the keyboard
How to add keyboard shortcuts using keyboardShortcut() | SwiftUI by Example
How to add keyboard shortcuts using keyboardShortcut()
How to make a TextField expand vertically as the user types | SwiftUI by Example
How to make a TextField expand vertically as the user types