根据键盘的可用性平滑地隐藏和显示按钮

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

所以我在键盘出现时在键盘顶部显示一个按钮,然后在键盘关闭时隐藏它但动画流程不够流畅

我想用键盘上下移动(不阻塞 UI)

图片:

当键盘出现时,您可以看到键盘还没有完全出现,但我的按钮在这里

当它隐藏时,仍然没有完全关闭,但按钮消失了

我的代码:

代码:

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 
    }
}

您应该应用正确的动画:

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

并且不使用 0.3,而是从 UIKeyboardAnimationDurationUserInfoKey 中获取 timeInterval