UIKit Dynamic是iOS7 新增的一組類和方法,可賦予UIView逼真的行爲和特徵,不須要寫動畫效果那些繁瑣的代碼,讓開發人員可以輕鬆地改善應用的用戶體驗。一共有6個可用於定製UIDynamicAnimator的類,這裏先只簡單介紹下碰撞的動畫效果,即UICollisionBehavior。須要簽定一個代理協議:UICollisionBehaviorDelegate。其餘效果,後續更新,敬請期待。ide
注意:dragonImageView和frogImageView記得要初始化還有: UIDynamicAnimator、UIGravityBehavior、 UICollisionBehavior必定要聲明成屬性或者全局變量,不然不會產生動畫效果!動畫
#import "ICFCollisionViewController.h"代理
@interface ICFCollisionViewController ()對象
{開發
UIImageView *dragonImageView;it
UIImageView*frogImageView;io
}import
@end變量
@implementation ICFCollisionViewController用戶體驗
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[superviewDidLoad];
// 初始化力學動畫生成器
UIDynamicAnimator *animator = [[UIDynamicAnimatoralloc]initWithReferenceView:self.view];
// 建立重力下落效果的對象
UIGravityBehavior *gravityBehavior = [[UIGravityBehavioralloc]initWithItems:@[frogImageView,dragonImageView]];
//設置重力加速度,水平和豎直方向
[gravityBehavior setGravityDirection:CGVectorMake(0.0f, 0.3f)];
// 建立碰撞效果的對象
UICollisionBehavior* collisionBehavior = [[UICollisionBehavioralloc]initWithItems:@[frogImageView,dragonImageView]];
// 物體的碰撞模式共有三種:UICollisionBehaviorModeItems(物體相互碰撞)
UICollisionBehaviorModeBoundaries(物體不相互碰撞,只與邊界碰撞)
UICollisionBehaviorModeEverything(既與物體碰撞又與邊界碰撞)
[collisionBehavior setCollisionMode:UICollisionBehaviorModeEverything];
//此代碼的做用是將self.view的邊框做爲碰撞邊界,必須設置爲YES,不然不會生成碰撞效果
collisionBehavior.translatesReferenceBoundsIntoBoundary =YES;
[animatoraddBehavior:gravityBehavior];
[animatoraddBehavior:collisionBehavior];
collisionBehavior.collisionDelegate =self;
}
-(void)collisionBehavior:(UICollisionBehavior *)behavior beganContactForItem:(id<UIDynamicItem>)item withBoundaryIdentifier:(id<NSCopying>)identifier atPoint:(CGPoint)p
{
NSLog(@"開始碰撞時觸發的方法");
}
-(void)collisionBehavior:(UICollisionBehavior *)behavior endedContactForItem:(id<UIDynamicItem>)item withBoundaryIdentifier:(id<NSCopying>)identifier
{
NSLog(@"結束碰撞時觸發的方法");
}
@end