Woo Jia Hao Woo Jia Hao - 3 months ago 30
iOS Question

UIKeyboardWillHideNotification delay in animation

I have registered the two UIKeyboardNotifications (keyboardWillShow and keyboardWillHide) and both are being triggered. The issue comes in when the animation for textfield to move back to the original position only gets fired after the keyboard disappears. Is there anyway to reduce the lag between getting the notification and animating the textfield?

func keyboardWillShow(notification: NSNotification) {
let info = notification.userInfo!
let keyboardFrame : CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
duration = (info[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue)
let rawAnimationCurve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).unsignedIntValue << 16
animationCurve = UIViewAnimationOptions(rawValue: UInt(rawAnimationCurve))
let moveAmount = keyboardFrame.height
UIView.animateWithDuration(duration!, delay:0, options: animationCurve, animations: {
self.txtfield.transform = CGAffineTransformMakeTranslation(0.0, -self.moveAmount)
}, completion:nil)
}

func keyboardWillHide(notification: NSNotification) {
UIView.animateWithDuration(duration, delay:0, options:animationCurve, animations: {
self. txtfield.transform = CGAffineTransformMakeTranslation(0.0, 0.0)
}, completion:nil)
}


GIF image here

Answer

Realised a problem, it was a careless mistake by me.

Added :

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(viewController.keyboardDidHide), name: UIKeyboardWillHideNotification, object: nil)

instead of :

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(viewController.keyboardWillHide), name: UIKeyboardWillHideNotification, object: nil)