Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Keyboard Observer via NSNotificationCenter doesn't work

I'm trying to implement a simple keyboard observer in my iOS 8 Swift app but it really doesn't work. This is the code im currently using:

override func viewDidAppear(animated: Bool) {
    NSNotificationCenter().addObserver(self, selector: Selector(keyboardWillAppear()), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter().addObserver(self, selector: Selector(keyboardWillHide()), name: UIKeyboardWillHideNotification, object: nil)
}

override func viewDidDisappear(animated: Bool) {
    NSNotificationCenter().removeObserver(self)
}

func keyboardWillAppear() {
    logoHeightConstraint.constant = 128.0
}

func keyboardWillHide() {
    logoHeightConstraint.constant = 256.0
}

Strangely both functions to react to the keyboard are called once after starting the app. Nothing happens when I enter or leave a textfield. What am I doing wrong? And by the way: Is altering a constraint the best solution for changing the size of an image?

I really appreciate your help!

like image 502
stoeffn Avatar asked Nov 30 '22 18:11

stoeffn


2 Answers

Calling NSNotificationCenter() is instantiating a new NSNotificationCenter each time you call it. Try using NSNotificationCenter.defaultCenter() instead.

like image 134
Patrick Goley Avatar answered Dec 11 '22 00:12

Patrick Goley


//keyboard observers 
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillAppear"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide"), name: UIKeyboardWillHideNotification, object: nil)




func keyboardWillAppear() {
    println("Keyboard appeared")
}

func keyboardWillHide() {
    println("Keyboard hidden")
}
like image 33
JSA986 Avatar answered Dec 10 '22 23:12

JSA986