获取小键盘高度
@ObservedObject private var keyboard = KeyboardResponder()
keyboard.currentHeight
通过小键盘高度判断是否需要添加灰色背景,点击灰色背景隐藏小键盘1 2 3 4 5 6 7 8 9 10 11 12 13 14
| if keyboard.currentHeight != 0 { Color.gray .edgesIgnoringSafeArea(.all) .opacity(0.4) .onTapGesture { withAnimation(.spring()){ UIApplication.shared.windows.forEach { (window) in if window.isKeyWindow { window.endEditing(true) } } } } }
|
效果图
![通过监听小键盘高度添加背景,通过点击背景隐藏小键盘](https://cdn.jsdelivr.net/gh/sakiraven/imgs/blog/%E9%9A%90%E8%97%8F%E5%B0%8F%E9%94%AE%E7%9B%98%E6%95%88%E6%9E%9C%E5%9B%BE.gif)
keyboardhandle.swift1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| import UIKit import Foundation import SwiftUI import Combine class KeyboardResponder: ObservableObject { private var _center: NotificationCenter @Published var currentHeight: CGFloat = 0
init(center: NotificationCenter = .default) { _center = center _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) }
deinit { _center.removeObserver(self) }
@objc func keyBoardWillShow(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { currentHeight = keyboardSize.height } }
@objc func keyBoardWillHide(notification: Notification) { currentHeight = 0 } }
class KeyboardHeightHelper: ObservableObject { @Published var keyboardHeight: CGFloat = 0
init() { self.listenForKeyboardNotifications() } private func listenForKeyboardNotifications() { NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: .main) { (notification) in guard let userInfo = notification.userInfo, let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } self.keyboardHeight = keyboardRect.height }
NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidHideNotification, object: nil, queue: .main) { (notification) in self.keyboardHeight = 0 } } }
|