Swift中可以通过NotificationCenter来监听键盘的通知,获取键盘的高度和动画时间。

首先,在需要监听键盘的地方,注册键盘通知:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

然后,实现键盘弹出和收回的通知方法:

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardHeight = keyboardSize.height
        let animationDuration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        // 处理键盘弹出逻辑
        // ...
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if let animationDuration = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue {
        // 处理键盘收回逻辑
        // ...
    }
}

在键盘弹出通知中,通过keyboardFrameEndUserInfoKey获取键盘的frame,并计算出键盘的高度。通过keyboardAnimationDurationUserInfoKey获取键盘的动画时间。

在键盘收回通知中,通过keyboardAnimationDurationUserInfoKey获取键盘的动画时间。

记得在不需要监听键盘的地方,移除键盘通知:

NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
``
Swift实现监听键盘通知键盘高度和动画时间