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

标签 ios swift2 ios-animations

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

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

图片:

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

enter image description here

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

enter image description here

我的代码:

代码:

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

关于ios - 根据键盘的可用性平滑地隐藏和显示按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38997410/

相关文章:

ios - Futura Condensed ExtraBold 在带有 UIFontDescriptor 的 ios 8 中不起作用

ios - 当我在 iOS 中滚动 UITableView 时,cellForRowAtIndexPath 无法正确显示单元格

ios - Swift:按字母顺序对对象数组进行排序

ios - 使用 Xcode 7 和 Swift 2 编写项目时升级到 Xcode 7.1 是否安全

ios - 在 Swift 4 中的 TabBar 下方绘制关闭过渡

ios - 如何为页面 View Controller 提供 "Cover Vertical"过渡样式

ios - 将 UIView 中的位置转换为 SKScene

objective-c - 使用未声明的类型 'XXX',Xcode 7.3,swift 2.2

ios - 快速滑动手势识别器

ios - 扩展 UIViewControllerAnimatedTransitioning 时出现段错误