@State private var isKeyboardVisible = false
if isKeyboardVisible {
Button {
hideKeyboard()
} label: {
Color.clear.edgesIgnoringSafeArea(.all)
}
}
.onReceive(keyboardPublisher) { newIsKeyboardVisible in
print("Is keyboard visible? ", newIsKeyboardVisible)
isKeyboardVisible = newIsKeyboardVisible
}
import Foundation
import SwiftUI
import Combine
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from: nil, for:nil)
}
}
protocol KeyboardReadable {
var keyboardPublisher: AnyPublisher<Bool, Never> { get }
}
extension KeyboardReadable {
var keyboardPublisher: AnyPublisher<Bool, Never> {
Publishers.Merge(
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillShowNotification)
.map { _ in true },
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillHideNotification)
.map { _ in false }
)
.eraseToAnyPublisher()
}
}
func hideKeyboard() {
UIApplication.shared.endEditing()
}
https://stackoverflow.com/questions/65784294/how-to-detect-if-keyboard-is-present-in-swiftui
댓글
댓글 쓰기