Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build an Interactive Story App with Swift Personalizing the Story Communicating Via Notifications

Emin Grbo
Emin Grbo
13,092 Points

#selector issue in Swift 4

When i use "#selector" on the following code:

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

I get an error saying my methods needs to have "@objc", so i added that:

  @objc func keyboardWillShow (_ notification: Notification) {
    print("Will show")
  }

however, i don't get the print info in my console. I had this problem with #selector before but @objc solved the issue, just not sure why this is not wroking here.

Have you tried removing the ViewController before the keyboardWillShow?

Like this.

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

2 Answers

NIKHIL GUPTA
NIKHIL GUPTA
9,724 Points

Change Notification.Name.UIKeyboardWillShow to UIResponder.keyboardWillShowNotification.

Correct, but also Kind of weird in the Apple API it also states this property in the Notifcation.Name.keyboardWillShowNotification and also in the UIResponder class.

Jason Gallant
Jason Gallant
8,437 Points

While I'm just barely a Swift beginner at this point, my understanding is that this behavior was inferred prior to Swift 4, so you didn't need to explicitly include the @objc in the function declaration. Since Swift 4, however, you need to include it except in some very specific cases which are above my pay grade at the moment if you want to be able to call it using a selector.

Hope that helps.