'Possible to achieve `ScrollView` interactive keyboard dismissal in SwiftUI?
https://developer.apple.com/documentation/uikit/uiscrollview/keyboarddismissmode/interactive
On a typical UIScrollView, one may set this property to have the keyboard dismiss interactively alongside a scroll.
Is it possible to achieve this in SwiftUI? If it’s not directly available on ScrollView, I assume it’s perhaps possible by embedding a UIScrollView directly. 🤔
Solution 1:[1]
Looking at the SwiftUI documentation it doesn't seem like this is possible yet. I think your best option would be to wrap an UIScrollView into an UIViewRepresentable see here for the dev talk. I found a tutorial for a UIScrollView here you will just need to add the KeyboardDismissmode to the code
Solution 2:[2]
I add the code in my ContentView's onAppear modifier. It can be onDrag or .interactive depends on when you want to dismiss keyboard:
struct ContentView: View {
var body: some View {
Text("Hello World")
.onAppear {
UITableView.appearance().keyboardDismissMode = .onDrag
}
}
}
Solution 3:[3]
Yes,
add this code to init()
init() {
// on a list:
// UITableView.appearance().keyboardDismissMode = .interactive
UIScrollView.appearance().keyboardDismissMode = .interactive
}
Solution 4:[4]
Also want to point out that jsbeginnerNodeJS's answer also works on any scrollable view, such as List. For example:
struct ContentView: View {
@ObservedObject private var viewModel = GistsViewModel()
var body: some View {
NavigationView {
VStack {
SearchBar(text: $viewModel.searchText)
List {
ForEach(viewModel.gists) { gist in
NavigationLink(destination: SafariView(url: gist.htmlURL)
.navigationBarTitle("")
.navigationBarHidden(true)) {
GistView(gist: gist)
}
}
}
.navigationBarTitle(Text("GitHub Gists"))
.edgesIgnoringSafeArea(.bottom)
}
}
}
init() {
UIScrollView.appearance().keyboardDismissMode = .interactive
}
}
Solution 5:[5]
Yes you can, please refer to https://github.com/michaelhenry/KeyboardAvoider
Either wrap the view inside “KeyboardAvoider {}”
Or
Use the ViewModifier “.avoidKeyboard()”
Solution 6:[6]
For those who's using SwiftUI 'List' and want to dismiss keyboard, use below instead. UIScrollView dismisses keyboard on emoji keyboard horizontal scroll.
UITableView.appearance().keyboardDismissMode = .onDrag
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yawnobleix |
| Solution 2 | |
| Solution 3 | SwiftiSwift |
| Solution 4 | |
| Solution 5 | Michael Henry |
| Solution 6 | Steve Ham |
