Playback speed
×
Share post
Share post at current time
0:00
/
0:00
Transcript

SwiftUI FYI #13 - Keyboard Dismissal

Keyboard Dismissal with SwiftUI ScrollViews

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 XThreads, and LinkedIn

Thanks for reading Your Weekly SwiftUI FYI 💡! Subscribe for free to receive new posts and support my work.


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()
}

Discussion about this podcast

Your Weekly SwiftUI FYI 💡
Your Weekly SwiftUI FYI 💡