NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to dismiss the keyboard when the user scrolls

Paul Hudson    @twostraws   

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)
                TextEditor(text: $bio)
                    .frame(height: 400)
                    .border(.quaternary, width: 1)

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:

  • 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.

Hacking with Swift is sponsored by Stream

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.

Try now!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.9/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.