扬庆の博客

tableView 处理键盘弹出挡住输入框

字数统计: 293阅读时长: 1 min
2021/09/28 Share

场景: 自定义cell内部通过Autolayout 布局, 使cell content 能够自动撑开。

1
2
3
4
5
6
7
8
9
cell.editCallBack = {[weak self] in
guard let self = self else { return }

UIView.performWithoutAnimation {
self.tableView.beginUpdates()
self.tableView.endUpdates()
self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
}
}
1
2
3
UIView.performWithoutAnimation {
// cell 刷新
}

上面代码能够主线程刷新 cell 布局 , 并且没有闪屏幕情况。

监听键盘的弹出

别忘了移除监听。

首先要拿到键盘的高度,

然后tableview距离底部高度( 一般都是安全区域的高度, 全屏显示 ),

得到差值就是 contentEdgeInset 要偏移的高度 。

let deltaHeight = keyboardSize!.height - tableViewBottomSpace

1
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
NotificationCenter.default.rx
.notification(UIResponder.keyboardWillShowNotification)
.subscribe(onNext: {[weak self] notification in
guard let self = self,
let userInfo = notification.userInfo else { return }
let deltaHeight = keyboardSize!.height - tableViewBottomSpace
let keyboardValue = userInfo[UIResponder.keyboardFrameEndUserInfoKey]
let keyboardSize = (keyboardValue as AnyObject).cgRectValue?.size
let duration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
let tableViewBottomSpace: CGFloat = 114

UIView.animate(withDuration: duration ?? 0.5) {
self.tableView.contentInset = UIEdgeInsets(top: 0,
left: 0,
bottom: deltaHeight,
right: 0)
}

}).disposed(by: disposeBag)

NotificationCenter.default.rx
.notification(UIResponder.keyboardWillHideNotification)
.subscribe(onNext: {[weak self] notification in
guard let self = self else { return }
let duration = (notification.userInfo?[UIResponder.keyboardWillHideNotification] as? NSNumber)?.doubleValue
UIView.animate(withDuration: duration ?? 0.5) {
self.tableView.contentInset = UIEdgeInsets.zero
}
}).disposed(by: disposeBag)

最后移除对键盘的监听

1
2
3
deinit {
notificationCenter.default.removeObserver(self)
}
CATALOG
  1. 1. 监听键盘的弹出