theaxeH
theaxeH

Reputation: 21

swift: keyboard observer does not work

I am still in the (swift) learning process, so please forgive any horrible oversights from my side. I did search through every possible question in this context and tried all different suggestions, ideas and permutations of the syntax I could find. No luck so far. Below code should just allow me to react to keyboard state changes:

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)
}

But it crashes every time with

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[moreKeybNotifications.ViewController keybShow:]: unrecognized selector sent to instance 0x7fa130710e60'"

when tapping/clicking a textfield.

I even commented out the 2 functions keybShow and keybHide at one point, the same crash still happened. Any input would be greatly appreciated!

Upvotes: 2

Views: 921

Answers (2)

Vimal Saifudin
Vimal Saifudin

Reputation: 1845

    NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

Upvotes: 0

Aderstedt
Aderstedt

Reputation: 6518

You've defined keybShow and keybHide as local functions within viewDidLoad. Put them in the class ViewController scope instead.

override func viewDidLoad() {
    super.viewDidLoad()
}

func keybShow(notification: NSNotification) {
    println("kb show")
}


func keybHide(notification: NSNotification) {
    println("kb hide")
}

Upvotes: 3

Related Questions