Skip to content

Instantly share code, notes, and snippets.

@hhhello0507
Created March 25, 2025 12:43
Show Gist options
  • Save hhhello0507/d97eb0b80188462450df3f607236030d to your computer and use it in GitHub Desktop.
Save hhhello0507/d97eb0b80188462450df3f607236030d to your computer and use it in GitHub Desktop.
import SwiftUI
import UIKit
public extension View {
func hideKeyboardWhenTap() -> some View {
self.onTapGesture(perform: hideKeyboard)
}
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
extension UIApplication {
func hideKeyboard() {
guard let window else { return }
let tapRecognizer = UITapGestureRecognizer(target: window, action: #selector(UIView.endEditing))
tapRecognizer.cancelsTouchesInView = false
tapRecognizer.delegate = self
window.addGestureRecognizer(tapRecognizer)
}
}
extension UIApplication: @retroactive UIGestureRecognizerDelegate {
public func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment