我尝试获取键盘的高度以在键盘显示时更新表格内容插入;但是来自UIResponder.keyboardWillShowNotification
的通知显示了具有安全区域高度的框架。有没有办法获得实际的键盘框架?
键盘高度的代码:
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
print("show: (keyboardHeight)")
tableView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 18 + keyboardHeight, right: 0)
tableView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 18 + keyboardHeight, right: 0)
}
但这给出了以下键盘的高度:https://i.stack.imgur.com/Y3uqk.jpg
我想要什么:https://i.stack.imgur.com/3xUbW.jpg
首先你必须得到安全区域的底部高度,然后 将其从键盘总高度中排除。这样你只会得到 键盘高度,无底部安全区域。
佩苏多代码:
让键盘高度 = 您的键盘高度 - 底部填充
if #available(iOS 11.0, *) {
let window = UIApplication.shared.keyWindow
let bottomPadding = window?.safeAreaInsets.bottom
}
希望对您有所帮助。
在计算约束值时,尝试减去安全区域底部插图的高度。
下面是处理 UIKeyboardWillChangeFrame 通知的示例实现。
@objc private func keyboardWillChange(_ notification: Notification) {
guard let userInfo = (notification as Notification).userInfo, let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else { return }
let newHeight: CGFloat
if #available(iOS 11.0, *) {
newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
} else {
newHeight = value.cgRectValue.height
}
myConstraint.value = newHeight
}