Skip to content

Instantly share code, notes, and snippets.

@JoaoCardoso00
Created December 10, 2023 18:40
Show Gist options
  • Save JoaoCardoso00/f09f020e529e7c9f12ce2044fef11218 to your computer and use it in GitHub Desktop.
Save JoaoCardoso00/f09f020e529e7c9f12ce2044fef11218 to your computer and use it in GitHub Desktop.
Helper function to improve UX on keyboard in swiftUI applications
//
// DismissKeyboardOnTap.swift
//
// Created by joao cardoso on 10/12/23.
//
import SwiftUI
public extension View {
func dismissKeyboardOnTap() -> some View {
modifier(DismissKeyboardOnTap())
}
}
public struct DismissKeyboardOnTap: ViewModifier {
public func body(content: Content) -> some View {
#if os(macOS)
return content
#else
return content.gesture(tapGesture)
#endif
}
private var tapGesture: some Gesture {
TapGesture().onEnded(endEditing)
}
private func endEditing() {
UIApplication.shared.connectedScenes
.filter { $0.activationState == .foregroundActive }
.map { $0 as? UIWindowScene }
.compactMap { $0 }
.first?.windows
.filter { $0.isKeyWindow }
.first?.endEditing(true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment