Created
September 24, 2020 15:52
-
-
Save IuriiIaremenko/d658ad763d1500c3d0fe255c44c88fa7 to your computer and use it in GitHub Desktop.
SwiftUI dismiss keyboard on sroll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#if canImport(UIKit) | |
extension View { | |
func dismissKeyboard() { | |
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) | |
} | |
} | |
#endif | |
extension View { | |
public func dismissKeyboardOnDrag() -> some View { | |
self.gesture(DragGesture().onChanged { _ in self.dismissKeyboard() }) | |
} | |
} | |
// Example | |
struct EventsListView: View { | |
let events: [EventDTO] | |
@State private var searchText = "" | |
private var eventsSearched: [EventDTO] { | |
searchText.isEmpty ? events : events.filter { $0.title.lowercased().contains(searchText.lowercased())} | |
} | |
var body: some View { | |
ScrollView(.vertical, showsIndicators: false) { | |
VStack { | |
SearchBar(text: $searchText, placeholder: "Search Events") | |
ForEach(eventsSearched) { event in | |
FeaturedEventView(model: event) | |
} | |
} | |
} | |
.dismissKeyboardOnDrag() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment