【问题标题】:Textfield frame animation is not in sync with keyboard animation duration文本字段帧动画与键盘动画持续时间不同步
【发布时间】:2018-03-30 21:36:58
【问题描述】:

我有一个文本字段,我可以使用键盘将其向上移动。但是,动画不同步。文本字段框架比键盘持续时间提前约 0.5 秒向上移动。我认为它们应该是同步的,但我无法找出问题所在。下面是我的键盘功能动画。

通知观察者:

NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow), name: .UIKeyboardWillShow, object: nil)

动画功能:

    @objc func handleKeyboardWillShow(notification: NSNotification){
    if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue, let keyboardDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double, let tabBarHeight = tabBarController?.tabBar.frame.size.height{
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height

        UIView.animate(withDuration: keyboardDuration, animations: {
                    self.textfieldBottomeConstraint?.constant = -keyboardHeight + tabBarHeight
            self.view.layoutIfNeeded()
        })
    }

}

我确实尝试过,但仍然得到相同的结果:

self.textfieldBottomeConstraint?.constant = -keyboardHeight + tabBarHeight

UIView.animate(withDuration: keyboardDuration, animations: {

    self.view.layoutIfNeeded()

})

【问题讨论】:

  • 您还需要保持曲线同步。见UIKeyboardAnimationCurveUserInfoKey
  • 我认为是因为您将 tabBarHeight 添加到 height ,所以动画持续时间不正确
  • 我还删除了标签栏高度进行测试,但仍然得到相同的结果

标签: swift uiview uiviewanimation nsnotificationcenter


【解决方案1】:

尝试两件事:

  1. 尝试使用UIKeyboardWillChangeFrame 而不是UIKeyboardWillShow

  2. 如果它没有改变任何东西,请尝试在动画中使用键盘曲线。

    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationCurve(context.animationCurve)
    UIView.setAnimationDuration(context.animationDuration)
    

    曲线和持续时间在哪里

    public var animationCurve: UIViewAnimationCurve {
        let value = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        return UIViewAnimationCurve(rawValue: value.intValue)!
    }
    
    public var animationDuration: Double {
        return userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
    }
    

【讨论】:

    【解决方案2】:

    键盘通知还包括一个 UIKeyboardAnimationCurveUserInfoKeyUIKeyboardAnimationDurationUserInfoKey。您可以查询这些值以确保您的动画使用与键盘相同的持续时间和动画曲线。 (在 Xcode 帮助系统中搜索“Keyboard Notification User Info Keys”可以找到键盘通知中提供的所有不同的键/值对。

    【讨论】:

    • 问题中的代码已经获取并使用了UIKeyboardAnimationDurationUserInfoKey 值。
    • 哦,原来如此。那个位在文本视图的右边缘,所以我错过了它,并假设keyboardDuration 是一个常数。
    猜你喜欢
    • 2012-11-17
    • 1970-01-01
    • 2016-09-24
    • 2018-06-15
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多