2015-02-09 24 views
3

我有一个在InterfaceBuilder中配置好的ViewController,用它的所有子视图使用AutoLayout。布局工作正常。当Autolay在玩时用UIDynamicAnimator进行动画制作

我想使用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) 

回答

4

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

基本上,UIKit Dynamics确实不是与自动布局很好地发挥。基本上规则是改变框架/中心的东西是违背自动布局 - 这正是UIKit Dynamics所做的。你没有遇到问题的唯一原因是,偶然地,布局不会发生在你正在动画的视图上。

测试的方法是这样的。运行你的代码,然后(当动画完成,可能还需要使用延迟性能要)运行

self.view.layoutIfNeeded 

这导致布局发生。如果事情在那个时候出现,它会暴露这个问题。

+0

谢谢,马特。在这种情况下,我将动画返回到其最终布局,并且在动画过程中没有其他布局更改发生,因此在这种情况下使用也许可以。 3个问题给你:1.你是否说如果在动画过程中发生布局,那会导致问题? 2.之前从未听说过“延迟的表现”,但Google向我展示了这是一件事情。你能指出我的任何资源吗? 3.如果您想在使用自动布局的视图控制器中设置动画(例如,弹跳或摆动)UI元素,您会怎么做? – stone 2015-02-12 04:37:06

+1

@skypecakes 1.是 - 或之后发生。但是,如果您的动画将所有内容都返回到原来的位置,您将不会看到问题,因为您所做的(使用框架)以及自动布局将会执行的操作(使用约束)具有相同的结果。 2.见我的书:http://www.apeth.com/iOSBook/ch11.html#_delayed_performance 3.大主题,但看到我的文章在这里:http://stackoverflow.com/questions/12943107/how-do- i-adjust-the-anchor-point-of-a -layer-when-auto-layout-is-being-used/14105757#14105757 – matt 2015-02-12 17:38:18

+0

再次感谢。我现在正在阅读你对延迟表现的讨论。关于#1和#3,我必须承认,我对iOS中的动画知之甚少,无法理解你的论文,甚至不知道我是如何在动画中使用帧的!我喜欢深度潜水,花费足够的时间来理解它。你如何学习如此多的动画?有任何建议的人开始? – stone 2015-02-12 23:57:56

0

是,UIDynamicAnimator正常工作与自动版式。我有一个应用程序,严重依赖UIDynamicAnimator并使用约束,并且它工作正常。我发现的唯一问题是UIView animateWithDuration不能与约束一起工作,但是这种方法无论如何都不适用于UIDynamicAnimator。 希望它有帮助:)

相关问题