remy boys remy boys - 3 months ago 11
iOS Question

smoothly hide and show a button according to keyboard's availability

so i'm showing a button on top of my keyboard when keyboard is appearing and then hiding it when keyboard dismissed but the flow of animation is not smooth enough

i want to it come up and down with keyboard (without blocking the UI)

images:

WHEN KEYBOARD APPEARS , YOU CAN SEE THAT KEYBOARD IS STILL NOT FULLLY APPEARED BUT MY BUTTON IS HERE

enter image description here

AND WHEN IT HIDES , STILL NOT FULLY DISMISSED BUT BUTTON IS GONE

enter image description here

my code :

CODE:

viewDidLoad ...... {
// here we have notification observers for tracking the states of Keyboard
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LaunchScreenViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)

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

}


func keyboardWillShow(notification:NSNotification) { // in this function i'm changing the origin (Y) axis of my button os that it can appear on top of my keyboard
let userInfo:NSDictionary = notification.userInfo!
let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.CGRectValue()
UIView.animateWithDuration(0.3) {

self.nextButtonConstraint.constant = keyboardRectangle.height
}
}

func keyboardWillHide(notification:NSNotification) {
UIView.animateWithDuration(0.5) {

self.nextButtonConstraint.constant = -50 // here i'm making my button out of screen bounds
}
}

Answer

You should apply correct animation:

self.nextButtonConstraint.constant  = keyboardRectangle.height
UIView.animateWithDuration(0.3) {
    <outlet to nextButton>.layoutIfNeeded() // insert correct value in <>
}

And don't use 0.3, but take timeInterval from UIKeyboardAnimationDurationUserInfoKey

Comments