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 监听键盘通知:获取键盘高度和动画时间

原文地址: https://www.cveoy.top/t/topic/pv80 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录