我有一个ViewController,它已在InterfaceBuilder中配置为对其所有子视图使用AutoLayout。布局工作正常。
我想使用UIDynamicAnimator提供的酷重力效果使其中一个子视图反弹。我并不认为这适用于AutoLayout,但我尝试了它,确实如此。它运作得很好!
我的问题是,这是预期的行为吗?是否会在某处造成问题? Apple是否提供有关组合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)
答案 0 :(得分:5)
我的问题是,这是预期的行为吗?是否会在某处造成问题? Apple是否提供有关组合AutoLayout和UIDynamicAnimators的任何指导?
基本上,UIKit Dynamics 不可以很好地配合自动布局。基本上规则是改变某些东西的框架/中心与自动布局相反 - 这正是UIKit Dynamics所做的。您没有遇到问题的唯一原因是,偶然地,您正在制作动画的视图上不会发生布局。
测试的方法是这样的。运行你的代码,然后(当动画完成时;可能你需要使用延迟性能)运行
self.view.layoutIfNeeded
这导致布局发生。如果事情在那一刻跳了起来,就会暴露出这个问题。
答案 1 :(得分:0)
是的,UIDynamicAnimator可以正常使用AutoLayout。我有一个严重依赖UIDynamicAnimator并使用约束的应用程序,它运行良好。我发现的唯一问题是UIView animateWithDuration不能使用约束,但该方法无论如何都不适用于UIDynamicAnimator。 希望它有所帮助:)