Created
December 10, 2023 18:40
-
-
Save JoaoCardoso00/f09f020e529e7c9f12ce2044fef11218 to your computer and use it in GitHub Desktop.
Helper function to improve UX on keyboard in swiftUI applications
This file contains 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
// | |
// 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