I'm trying to update this code to swift 3:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)`
So far, I've just tried the auto corrections given by the compiler. This results in code like this:
let notificationCenter = NotificationCenter.default()
notificationCenter.addObserver(self, selector: Selector(("keyboardWillShow:")), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: Selector(("keyboardWillHide:")), name: NSNotification.Name.UIKeyboardWillHide, object: nil)`
Unfortunately, that doesn't take me far, resulting in additional errors.
Has anyone solved this please?
Please note that I'm just trying how to write the notifications. I'm not (yet) trying to fix the notification functions.. Thanks
Swift 4.2 Xcode 10 (10L213o)
The main changes compared with Swift 3 are in the
UIWindow.keyboardWillShowNotification
andUIWindow.keyboardWillHideNotification
You can replace the deprecated string literal
Selector
with the type-checked#selector(Class.method)
pair:The
#selector
syntax is much safer, since Swift is able to check at compile time that the specified method actually exists.For more information about Swift selectors, see rickster's detailed answer.
You can perform keyboard notification on both version of Swift respectively.
Add Objserver:
Call function swift 3
Call function In swift 4
I fixed this issue by writing the code like this
For Swift 4.2
.UIKeyboardWillShow
is renamed toUIResponder.keyboardWillShowNotification
and.UIKeyboardWillHide
is renamed toUIResponder.keyboardWillHideNotification
In Swift 3.0
Keybord Show and Hide