持续时间不正确的UIView.animate无法正常工作

时间:2019-08-25 18:40:41

标签: ios swift xcode animation

UIView.animate在我的代码的“其他”部分中不起作用。但是,它在“ if”语句中工作得很好。有什么建议可能导致此问题吗?

    if notification.name == UIResponder.keyboardWillShowNotification ||
        notification.name == UIResponder.keyboardWillChangeFrameNotification {

        // Keyboard shows
        self.view.layoutIfNeeded()
        UIView.animate(withDuration: 0.25) {
            self.view.layoutIfNeeded()
            let heightHelper = self.bottomConstraint.constant
            self.bottomConstraint.constant = keyboardRect.height + 20

            self.bottomConstraintEmail.constant += keyboardRect.height + 20 - heightHelper
            self.anmeldenLabel.alpha = 0
            self.logoConstraint.constant = 45
        }
    } else {
        // Keyboard hides
        self.view.layoutIfNeeded()
        UIView.animate(withDuration: 0.5) {
            self.view.layoutIfNeeded()
            self.bottomConstraintEmail.constant = 337
            self.bottomConstraint.constant = 255.5
            self.logoConstraint.constant = 60
            self.anmeldenLabel.alpha = 1
        }
    }

1 个答案:

答案 0 :(得分:1)

@Don 是完全正确的:设置新的约束后,应调用layoutIfNeeded()

这应该可以正常工作:

if notification.name == UIResponder.keyboardWillShowNotification ||
    notification.name == UIResponder.keyboardWillChangeFrameNotification {

    // Keyboard shows
    let heightHelper = self.bottomConstraint.constant
    self.bottomConstraint.constant = keyboardRect.height + 20

    self.bottomConstraintEmail.constant += keyboardRect.height + 20 - heightHelper
    self.anmeldenLabel.alpha = 0
    self.logoConstraint.constant = 45

    UIView.animate(withDuration: 0.25) {
        self.view.layoutIfNeeded()
    }
} else {
    // Keyboard hides
    self.bottomConstraintEmail.constant = 337
    self.bottomConstraint.constant = 255.5
    self.logoConstraint.constant = 60
    self.anmeldenLabel.alpha = 1

    UIView.animate(withDuration: 0.5) {
        self.view.layoutIfNeeded()
    }
}