简体   繁体   中英

Animate UIView swap with layout constraints

I am swapping one UIView for another—removing one and adding the other, which works fine. I would like to animate the transition, which should be easy, but the problem is that I need to add layout constraints on the view I'm adding. (The constraints on the added view are different from those on the one I'm removing.)

I'm not trying to animate the change in constraints. They need to be in place so the view is shown at the correct size, and the correct size varies depending on the screen size.

Setting up the new constraints in the animation block obviously crashes because the view hierarchy isn't yet set up. Setting them in the completion block is too late—they get added, but the new view comes in wrong and doesn't lay out correctly with the new constraints until the next time I update the view, which causes the layout to "jump" from wrong to right.

UIView.transition(with: containerView,
                  duration: 0.3,
                  options: .transitionCrossDissolve,
                  animations: {
                    self.containerView.addSubview(targetView)
                    self.currentView.removeFromSuperview()
                  }, completion: { _ in
                    self.currentView = targetView
                    self.setupConstraints()
                  })

Is there a way to work around this? I feel like I'm missing something but I can't find it in the docs.

您可以在开始时设置所有视图和约束(例如,为targetView设置alpha = 0),然后仅设置动画视图的alpha和约束,在所有动画结束时删除不必要的视图。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM