Hey! 👋
Using a TextField embedded within a ScrollView is a common practice. An easy way to allow users to dismiss the keyboard is to respond to their interactions with the ScrollView, as they usually want to scroll to other content or they’re simply done with inputting text.
In today’s example, we achieve that with the immediate and interactive dismissal modes on ScrollView’s scrollDismissesKeyboard method.
🚨 Full code below and also on Github
🤝 Find more about me on saidmarouf.com. I’m also on X, Threads, and LinkedIn
import SwiftUI
struct KeyboardDismissView: View {
@State var input: String = ""
var body: some View {
ScrollView {
TextField("Enter Text", text: $input)
.padding()
.background(.secondary.opacity(0.5))
.clipShape(Capsule())
.padding()
Text("Swipe Down to Dismiss Keyboard".uppercased())
.multilineTextAlignment(.center)
.padding(44)
Text("Here's how you do it 👇")
.font(.title)
VStack(alignment: .leading) {
Text("**ScrollView {**")
Text(" // Contents").foregroundStyle(.gray)
Text("**}**")
Text("**.scrollDismissesKeyboard(.interactively)**")
}
.font(.system(size: 15))
.monospaced()
.foregroundStyle(.blue)
.padding()
.background(.black.opacity(0.8))
.cornerRadius(20)
}
.scrollDismissesKeyboard(.interactively)
.background(.black.gradient)
}
}
#Preview {
KeyboardDismissView()
}
SwiftUI FYI #13 - Keyboard Dismissal