在Swift中,可以通过NotificationCenter来实现监听键盘通知。具体实现步骤如下:

  1. 在需要监听键盘通知的地方,添加如下代码:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  1. 实现键盘将要显示和隐藏的方法:
@objc func keyboardWillShow(_ notification: Notification) {
    // 处理键盘将要显示的逻辑
}

@objc func keyboardWillHide(_ notification: Notification) {
    // 处理键盘将要隐藏的逻辑
}
  1. 在不需要监听键盘通知的地方,记得移除监听:
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)

在键盘将要显示和隐藏的方法中,可以通过notification.userInfo来获取键盘的相关信息,例如键盘的高度等

Swift实现监听键盘通知