Possible to achieve `ScrollView` interactive keyboard dismissal in SwiftUI?
Yes,
add this code to init()
init() {
// on a list:
// UITableView.appearance().keyboardDismissMode = .interactive
UIScrollView.appearance().keyboardDismissMode = .interactive
}
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
}
}
}
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
}
}