如何获得实际的键盘高度(键盘高度减去安全区域插图)

时间:2019-04-01 08:13:16

标签: ios swift

我尝试获取键盘的高度以在键盘显示时更新表格contentInsets;但是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://imgur.com/m0HR088

我想要什么: https://imgur.com/Lp6vHOm

2 个答案:

答案 0 :(得分:2)

  

首先,您必须获取“安全区域”底部的高度,然后   从键盘总高度中排除它。这样,您只会得到   键盘高度,没有底部安全区域。

伪代码:

  

let keyboardHeight =您的键盘高度-bottomPadding

if #available(iOS 11.0, *) {
    let window = UIApplication.shared.keyWindow
    let bottomPadding = window?.safeAreaInsets.bottom
}

希望它会对您有所帮助。

答案 1 :(得分:0)

在计算约束值时,请尝试减去安全区域底部插图的高度。

这是处理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
}