いよいよ9月20日にiPhone5sとiPhone5cが発売されるとともに,iOS7がリリースされます.
iOS7は見た目がフラットな感じになり,全体的にすっきりきれいな印象になったことに加え,開発に利用できるいくつかの機能が追加されています.
ビューのDynamicBehaviorもその一つです.
これは,UIViewが物理的な動きをすることをサポートするための機能です.例えば振り子的な動きをしたり,他のビューとぶつかったら跳ね返ったり,そんな動きを簡単に実現するためのクラスを提供してくれています.
今回はUIGravityBehaviorとUIDynamicAnimator,UIAttachmentBehaviorの3つのクラスを利用したサンプルを作ってみます.
@interface ViewController ()
@property (nonatomic) UIDynamicAnimator* animator;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIView *testView;
UIGravityBehavior *gb;
UIDynamicAnimator* animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
testView = [[UIView alloc] init];
testView.frame = CGRectMake(145,100,30,30);
testView.backgroundColor= [UIColor blueColor];
[self.view addSubview:testView];
UIAttachmentBehavior *attachmentBehavior = [[UIAttachmentBehavior alloc] initWithItem:testView attachedToAnchor:CGPointMake(145, 200)];
[animator addBehavior:attachmentBehavior];
gb = [[UIGravityBehavior alloc] initWithItems:@[testView]];
[gb setAngle:1.5707963267948966f magnitude:1.5f];
[animator addBehavior:gb];
self.animator = animator;
}
これだけ.これだけで
こんな感じの動きを実装することができます.ちなみにもう一つビューを作って,さらにUICollisionBehaviorのビヘイビアを作成し,それぞれのビューを登録すると,
こんな感じに自動で衝突エフェクトを追加してくれます.
動画はフレームレートが低いのであれですが,実際はなめらかに動きますよ.