Adam Rush

@Adam9Rush

6 June, 2022

This article was written using Xcode 14 and iOS 16

Introduction

You might be wondering how to dismiss the keyboard when using a ScrollView in SwiftUI and prompting the user to type something.

struct ContentView: View {
    @State var searchText = ""
    
    var body: some View {
        ScrollView {
            TextField("Search", text: $searchText)
            ForEach(0 ..< 50) { index in
                Text("Transaction \(index)")
                    .padding()
            }
        }
        .scrollDismissesKeyboard(.immediately)
    }
}

In your example, you’re listing rows of transactions with an TextField on the top. If you tap on the TextField and start scrolling you will notice the keyboard is dismissed immediately.

You have the following options:

  • .immediately
  • .automatic
  • .interactively
  • .never

The interactive option is when you fully scroll down past the keyboard.

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.