0

Trying to add keyboard observers in swift and getting error

NSNotificationcenter does not have a member names 'defaultCenter"

using

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

As advised from the following NSNotificationCenter addObserver in Swift Swift: Keyboard Observer via NSNotificationCenter doesn't work

If I remove defaultCenter I don't get the error but, also no observing of the keyboard

NSNotificationCenter().addObserver(self, selector: Selector("keyboardWillAppear"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter().addObserver(self, selector: Selector("keyboardWillHide"), name: UIKeyboardWillHideNotification, object: nil)
Community
  • 1
  • 1
JSA986
  • 5,870
  • 9
  • 45
  • 91

1 Answers1

4

defaultCenter is a class method (also called type method in Swift), therefore it is

NSNotificationCenter.defaultCenter()

and not

NSNotificationCenter().defaultCenter()

which would call the instance method defaultCenter() on the object created and returned by NSNotificationCenter().

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks Martin, I copy and pasted that snippet from the most upvoted answer here http://stackoverflow.com/questions/24999605/swift-keyboard-observer-via-nsnotificationcenter-doesnt-work and missed that. – JSA986 Sep 17 '14 at 20:29