開發過程當為了讓應用更絢,就加入一些動畫效果。CoreAnimation比較複雜,其實UIView的簡單動畫就可以滿足我們應用開發。UIView支援的動畫屬性有,frame, center, bounds,transform, alpha. 什麼意思呢,就是你可以修改這些屬性來完成動畫,比如設定frame,uiview就可以動了。下面看一段代碼:
// begin the animations block: [UIView beginAnimations:@"animationID" context:NULL]; // define how long the animation should take, in seconds. 0.5 is half a second. [UIView setAnimationDuration:3]; // animate the view itself by changing its frame: [theView setFrame:newFrame]; // or by changing its alpha value: [theView setAlpha:0.5]; // or by rotating it: theView.transform = CGAffineTransformMakeRotation(-0.7853981625); // 45 deg // optional: to execute code after the animation has finished, set the delegate: [UIView setAnimationDelegate:self]; // optional: set the animation curve: // UIViewAnimationCurveEaseIn: begins slowly, then speeds up // UIViewAnimationCurveEaseOut: begins fast, then slows down // UIViewAnimationCurveEaseInOut: begins slowly, faster in the middle, slows down at end // UIViewAnimationCurveLinear: same speed throughout [UIView setAnimationCurve: UIViewAnimationCurveEaseOut]; // start animating! [UIView commitAnimations];
這樣就完成了一個動畫效果, beginAnimatins:與commitAnimations這是必須寫的,中間設定你的屬性,這兒設定了三個屬性,分別是frame,alpha,transform. 這樣就完成了一個動畫,那個"animationID"隨便取名字。動畫的時間有多長呢, 有一個預設時間,在這兒我們設定的是3秒, 動畫有一個快慢,比如快進,setAnimationCurve就是控制什麼時候快進,什麼時候慢播。當這個動畫完了的時候,會有一個delegate方法調用:
- (void)animationDidStop:(NSString *)animID finished:(BOOL)didFinish context:(void *)context { if ( [animID isEqualToString:@"animationID"] ) { NSLog(@"move10 animation finished."); [self moveBack]; } else if ( [animID isEqualToString:@"moveBack"] ) { NSLog(@"done moving."); }}
在這兒你可以檢測到哪一個動畫完了,比如在這兒我們檢測到了animationID與moveBack.
是不是很簡單呀?
在iOS4以上,支援block了,所以用它使編程將更簡單,如傳統的動畫是這樣:
[UIView beginAnimations:nil context:nil];[UIView setAnimationDuration:0.5];[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:containerView cache:YES]; [containerView addSubview:subview]; [UIView commitAnimations];
如果用block的方式將是:
[UIView transitionWithView:containerView duration:0.5options:UIViewAnimationOptionTransitionCurlDownanimations:^ { [containerView addSubview:subview]; }completion:nil];
具體參看文檔:http://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html