背景
部分视图存在随键盘高度变化而自适应位置。所以需要监听键盘的高度变化。这里做个结合RxSwift做个简单封装。
使用参考
/// 底部栏键盘高度自适应
KeyboardHelper.shared.keyboardHeight.bind { [weak self] height in
guard let self = self else { return }
self.bottomView.snp.updateConstraints { make in
let offsetHeight = height > 0 ? height - UIWindow().safeAreaInsets.bottom : height
make.bottom.equalToSuperview().offset(-offsetHeight)
}
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}.disposed(by: rx.disposeBag)
实现
import RxRelay
/// 键盘辅助类
class KeyboardHelper: NSObject {
/// 单例
public static let shared = KeyboardHelper()
/// 键盘高度
public let keyboardHeight: PublishRelay<CGFloat> = .init()
private override init() {
super.init()
self.setup()
}
/// 键盘通知监听
private func setup() {
// 键盘即将出现
NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification).subscribe(onNext: { [weak self] value in
guard let self = self else { return }
let keyBoardEnd = (value.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect) ?? .zero
self.keyboardHeight.accept(keyBoardEnd.size.height)
}).disposed(by: rx.disposeBag)
// 键盘即将消失
NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification).subscribe(onNext: { [weak self] _ in
guard let self = self else { return }
self.keyboardHeight.accept(0)
}).disposed(by: rx.disposeBag)
}
}