Swift:键盘观察者不工作



我还在(快速)学习过程中,所以请原谅我这边的任何可怕的疏忽。我确实搜索了这方面所有可能的问题,尝试了我能找到的所有不同的建议、想法和语法排列。到目前为止还没有运气。下面的代码应该允许我对键盘状态的变化做出反应:

class ViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keybShow:",
        name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keybHide:",
        name: UIKeyboardWillHideNotification, object: nil)
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    func keybShow(notification: NSNotification) {
        println("kb show")
    }

    func keybHide(notification: NSNotification) {
        println("kb hide")
    }
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

但是每次使用

都会崩溃

由于未捕获异常'NSInvalidArgumentException'而终止应用程序,原因:'-[moreKeybNotifications.]ViewController keybShow:]:无法识别的选择器发送到实例0x7fa130710e60'"

当点击/点击一个文本域。

我甚至在一个点上注释掉了两个函数keybShow和keybHide,同样的崩溃仍然发生。任何输入将非常感激!

您已经将keybShowkeybHide定义为viewDidLoad中的局部函数。把它们放在class ViewController范围内。

override func viewDidLoad() {
    super.viewDidLoad()
}
func keybShow(notification: NSNotification) {
    println("kb show")
}

func keybHide(notification: NSNotification) {
    println("kb hide")
}
    NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

最新更新