Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEmin 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.
2 Answers
NIKHIL GUPTA
9,724 PointsChange Notification.Name.UIKeyboardWillShow
to UIResponder.keyboardWillShowNotification
.
osman musse
70 PointsCorrect, 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
8,437 PointsWhile 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.
Amazon Web
iOS Development Techdegree Student 4,092 PointsAmazon Web
iOS Development Techdegree Student 4,092 PointsHave you tried removing the ViewController before the keyboardWillShow?
Like this.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)