当Autolay正在播放时,用UIDynamicAnimator进行animation处理

我有一个已经在InterfaceBuilder中configuration的ViewController为所有子视图使用AutoLayout。 布局工作正常。

我想用UIDynamicAnimator提供的很酷的重力效果让其中一个子视图反弹。 我不认为这将适用于AutoLayout,但我尝试过,它确实如此。 它工作得很好!

我的问题是 ,这是预期的行为? 是否会在某个地方引起问题? 苹果公司是否提供关于AutoLayout和UIDynamicAnimators相结合的指导?

这里是代码,对于任何感兴趣的人:

var boundaryFrame = self.buttonBackgroundView.frame boundaryFrame = CGRect(x: 0, y: boundaryFrame.origin.y + (boundaryFrame.height + 1), width: self.view.frame.width, height: 2) self.animator = UIDynamicAnimator(referenceView: self.view) var gravity = UIGravityBehavior(items: [self.buttonBackgroundView]) gravity.magnitude = 0.5 var collision = UICollisionBehavior(items: [self.buttonBackgroundView]) var boundaryId: NSMutableString = NSMutableString(string: "bottomBoundary") let boundaryPath = UIBezierPath(rect: boundaryFrame) collision.addBoundaryWithIdentifier(boundaryId, forPath: boundaryPath) let bounceProperties = UIDynamicItemBehavior(items: [self.buttonBackgroundView]) bounceProperties.elasticity = 0.5 // Move it up before causing it to bounce down to its original location self.setMeUpTopConstraint.constant = 10 self.view.setNeedsUpdateConstraints() self.view.layoutIfNeeded() // Start animating animator.addBehavior(gravity) animator.addBehavior(collision) animator.addBehavior(bounceProperties) 

我的问题是,这是预期的行为? 是否会在某个地方引起问题? 苹果公司是否提供关于AutoLayout和UIDynamicAnimators相结合的指导?

基本上,UIKit Dynamics在自动布局方面效果不佳。 基本上规则是改变框架/中心的东西是违背自动布局 – 这正是UIKit动力学所做的。 你没有遇到问题的唯一原因是,偶然的情况下,布局不会发生在你正在animation的视图上。

testing的方法是这样的。 运行你的代码,然后(当animation完成时,可能你需要使用延迟的性能)运行

 self.view.layoutIfNeeded 

这会导致布局发生。 如果事情在那个时候跳,那就暴露了这个问题。

是的,UIDynamicAnimator适用于AutoLayout。 我有一个很大程度上依赖于UIDynamicAnimator的应用程序,并使用约束,它工作正常。 我发现唯一的问题是,UIView animateWithDuration不能与约束一起工作,但是这种方法不适用于UIDynamicAnimator。 希望能帮助到你 :)