具有约束的 UIViewAnimation 在 Swift 中不起作用

UIViewAnimation with constraint not working in Swift

我正在尝试创建一个动画,我想在父 UIViewController 加载后从右向左滑动 uiview,尽管我能够显示视图但动画不起作用。我的动画代码:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    view.isOpaque = false
    UIView.animate(withDuration: 1.0, delay: 1.0, options: .curveEaseOut, animations: {
        self.contentXConstraint.constant = 500
        self.contentXConstraint.constant = 80
    }) { (status) in

    }
}

我已经显示了父视图控制器 viewcontroller:

present(navController, animated: false, completion: nil)

将您的动画代码从 viewDidAppear 移动到 viewDidLayoutSubviews

你忘记了 self.view.layoutIfNeeded()

self.contentXConstraint.constant = 500
self.contentXConstraint.constant = 80

UIView.animate(withDuration: 1.0, delay: 1.0, options: .curveEaseOut, animations: {
   self.view.layoutIfNeeded()
}) { (status) in
}

来自 https://developer.apple.com/documentation/uikit/uiview/1622507-layoutifneeded

Use this method to force the view to update its layout immediately. When using Auto Layout, the layout engine updates the position of views as needed to satisfy changes in constraints

更新约束后需要添加layoutIfNeeded()方法

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    view.isOpaque = false
    UIView.animate(withDuration: 1.0, delay: 1.0, options: .curveEaseOut, animations: {
        self.contentXConstraint.constant = 500
        self.contentXConstraint.constant = 80
        self.view.layoutIfNeeded()
    }) { (status) in

    }
}