WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

How to dismiss the keyboard when the user scrolls

Paul Hudson    @twostraws   

Updated for Xcode 14.0 beta 1

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:

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

SPONSORED In-app subscriptions are a pain. The code can be hard to write, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app.

Explore the docs

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

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.