在 Swift 中,你可以通过使用 UITextView 或 UITextField 类来监听键盘事件。下面是一个简单的示例:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        textField.delegate = self
        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 userInfo = notification.userInfo {
            let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
            let keyboardHeight = keyboardFrame.height
            
            // 在这里你可以根据键盘的高度调整你的界面布局
            // 例如,将文本框的底部与键盘的顶部对齐
            textField.frame.origin.y = view.frame.height - keyboardHeight - textField.frame.height
        }
    }
    
    @objc func keyboardWillHide(notification: NSNotification) {
        textField.frame.origin.y = view.frame.height - textField.frame.height
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 当用户按下 Return 键时收起键盘
        textField.resignFirstResponder()
        return true
    }
}

这个示例中,我们首先将视图控制器声明为 UITextFieldDelegate,并在 viewDidLoad 方法中将 textField 的委托设置为视图控制器。然后,我们使用 NotificationCenter 来监听键盘的显示和隐藏事件,并在相应的方法中调整界面布局。最后,我们实现了 textFieldShouldReturn 方法来在用户按下 Return 键时收起键盘。

请注意,你需要在 Interface Builder 中将 UITextField 连接到视图控制器的 textField 属性

swift 监听键盘