我能以某种方式检测来自 iOS 键盘的事件吗?
我想在没有 UITextField
或任何此类对象的 UIViewController
上检测此类事件。
我只有四个圆圈,它们是 UIView
,我想在按下键盘上的按钮时用不同的颜色绘制它们。
最佳答案
您没有任何对象可以从键盘获取输入。要显示键盘,您的 View 中必须有 UITextField 或 UITextView 对象。
但这里是在 View Controller 中检测键盘事件的过程。您可以在 View Controller 上设置观察者以获取键盘通知。
要在 swift 3 中注册键盘通知,请将这些行写入 View Controller 的 viewDidLoad() 或 viewWillAppear() 方法中
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
然后在您的 View Controller 中实现两个方法 keyBoardWillHide(:) 和 keyBoardWillShow(:)
func keyBoardWillShow(notification: NSNotification) {
//handle appearing of keyboard here
}
func keyBoardWillHide(notification: NSNotification) {
//handle dismiss of keyboard here
}
关于iOS Swift 检测键盘事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43199794/