本文檔版權歸NickTang所有,沒有本人書面或電子郵件允許,不許轉載,摘錄,發表。多謝!
上一個文檔,我演示了timer的使用,並且形成了一個動畫,但是這個動畫可擴展性不好,我們需要更好的動畫實現技術,這裏UIView類提供了一些基本的功能。
1.新建一個view-based Application.(在iOS5中是Single View Application)
2.加入一個小的圖片,我用的是一個circle.png,長和寬都不要大於100.
3.在viewcontroller.xib上面做如下佈局
4. ViewController.h文件如下:
@interface subViewAnimationViewController : UIViewController {
IBOutlet UIButton *myButton;
IBOutlet UIImageView *myIV;
}
- (IBAction)startAnimation:(id)sender;
@end
5. ViewController.m文件如下:
@implementation subViewAnimationViewController
- (void)dealloc
{
[myIV release];
[myButton release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (void)viewDidUnload
{
[myIV release];
myIV = nil;
[myButton release];
myButton = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)startAnimation:(id)sender {
CGRect frame = myIV.frame;
frame.origin.y = 300;
[UIView beginAnimations:@"aa" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:2.0];
[myIV setFrame:frame];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(viewExchangeAnimationDidStop:finished:context:)];
[UIView commitAnimations];
}
- (void) viewExchangeAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
CGRect frame = myIV.frame;
frame.origin.y = 25;
[UIView beginAnimations:@"aa" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:2.0];
[myIV setFrame:frame];
[UIView commitAnimations];
}
@end
6.解釋代碼如下:
CGRect frame = myIV.frame;
frame.origin.y = 300;
[UIView beginAnimations:@"aa" context:nil];//開始一個動畫
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];//設置動畫先慢後快
[UIView setAnimationDuration:2.0];//設置動畫持續2秒
[myIV setFrame:frame];//動畫內容,從現有位置移動到frame指示的位置。
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(viewExchangeAnimationDidStop:finished:context:)];
//上面的兩句話設置,當動畫結束的時候,調用本類的viewExchangeAnimationDidStop:finished:context:函數
[UIView commitAnimations];//開始動畫
其他的代碼就不解釋了,
7.例子代碼