以今年的优点WWDC品行,我记得一些明年的元素。一些博客上找到了新的功能没有被记录。认为iOS 8尽心尽力。iOS 7该属性不随手记录为时已晚 :)ide
参考WWDC 2013的Session Videos《Getting Started with UIKit Dynamics》和《Advanced Techniques with UIKit Dynamics》。随手记了如下几点:动画
UIKit Dynamics是抽象出来封装好的二维物理引擎,并本身定义了UIKit物理世界的两个常量,用UIKit重力加速度1000p/s2替换了地球重力加速度,用UIKit牛顿第二定律每一单位的力可以使得100p*100p的view产生100p/s2的加速度来替换1F = 1Kg * 1m/s2。ui
从使用者的角度来看,UIKit Dynamics有例如如下几个角色:spa
UIDynamicAnimator —— 封装了底下的物理引擎,使得咱们可以方便地加入物理行为;code
UIDynamicBehavior —— 定义了物理行为的类型;对象
UIDynamicItem —— 參与物理动画的对象;blog
借用两张网上的照片来描写叙述三者之间的关系,分别来自http://www.teehanlax.com/blog/introduction-to-uikit-dynamics/ 和 WWDC 2013。ip
如下是详细的demo代码。ci
首先咱们建立UIDynamicAnimator:get
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];使用self.view做为參考系。
接着,建立要做用物理动画的视图对象。最好仍是为一个label:
UILabel *label = [[UILabel alloc] initWithFrame:(CGRect){100, 100, 100, 40}]; label.backgroundColor = [UIColor redColor]; [self.view addSubview:label];因而咱们可以在label上加入重力加速度和碰撞的物理效果:
UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[label]]; [self.animator addBehavior:gravityBehavior]; UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[label]]; collisionBehavior.translatesReferenceBoundsIntoBoundary = YES; [self.animator addBehavior:collisionBehavior];这就能建立出十分生动的物理动画了。
除此以外,咱们还可以在视图上加上做用力:
self.pushBehavior = [[UIPushBehavior alloc] initWithItems:@[label] mode:UIPushBehaviorModeInstantaneous]; self.pushBehavior.pushDirection = CGVectorMake(1.0f, 0); [self.animator addBehavior:self.pushBehavior];
这样。label就不是垂直往下掉了,而是有个水平做用力使得label撞向边缘。
为了使得动画更有趣,可以加点用户的交互:
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPanLabel:)]; [label addGestureRecognizer:panGesture];
#pragma mark - - (void)didPanLabel:(UIPanGestureRecognizer *)panGesture { UIGestureRecognizerState state = panGesture.state; if (state == UIGestureRecognizerStateEnded) { CGPoint velocity = [panGesture velocityInView:self.view]; self.pushBehavior.pushDirection = CGVectorMake(velocity.x / 1000, velocity.y / 1000); self.pushBehavior.active = YES; } }这项。当用户在施力动做中检测label当顶,label它会抛出。