我可以以某种方式检测来自iOS键盘的事件吗?
我想检测UIViewController
上没有UITextField
或任何此类对象的此类事件。
我只有四个UIView
的圆圈,当按下键盘上的按钮时,我想用不同的颜色绘制它们。
答案 0 :(得分:9)
您没有任何对象从键盘获取输入。要使键盘出现,您的视图中必须包含UITextField或UITextView对象。
但这是检测视图控制器中键盘事件的过程。您可以在视图控制器上设置观察者以获取键盘通知。
要在swift 3中注册键盘通知,请在视图控制器的viewDidLoad()或viewWillAppear()方法中使用write这些行
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
然后在视图控制器中实现两个方法keyBoardWillHide(:)和keyBoardWillShow(:)方法
func keyBoardWillShow(notification: NSNotification) {
//handle appearing of keyboard here
}
func keyBoardWillHide(notification: NSNotification) {
//handle dismiss of keyboard here
}
答案 1 :(得分:1)
您可以使用键盘处理程序
创建自己的视图//Example
class CustomKeyInput: UIControl, UIKeyInput{
//UIKeyInput
public var hasText: Bool { return false }
public func insertText(_ text: String){
print(#function)
print(text)
print(text.characters.count)
}
public func deleteBackward(){
print(#function)
}
//UIControl
override var canBecomeFirstResponder: Bool {return true}
}
//Usage
class ViewController: UIViewController {
@IBOutlet weak var keyView: CustomKeyInput!
override func viewDidAppear(_ animated: Bool) {
keyView.becomeFirstResponder()
}
}
答案 2 :(得分:0)
Swift 4.2
注册活动:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification , object:nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification , object:nil)
选择器:
@objc func keyboardWillShow(notification: NSNotification) {
let keyboardHeight = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
print(keyboardHeight)
}
@objc func keyboardWillHide(notification: NSNotification) {
let keyboardHeight = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
print(keyboardHeight)
}