1 前言
今天我們來學習使用 UIView 的動畫方法來移動你的視圖。
2 代碼執行個體
ZYViewController.m:
[plain]
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImage *xcodeImage = [UIImage imageNamed:@"Xcode.png"];
self.xcodeImageView = [[UIImageView alloc] initWithImage:xcodeImage];
//設定圖片的Frame
[self.xcodeImageView setFrame:CGRectMake(0.0f,0.0f, 100.0f, 100.0f)];
self.view.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.xcodeImageView];
}
-(void) viewDidAppear:(BOOL)paramAnimated{
[super viewDidAppear:paramAnimated];
//從左上方開始
[self.xcodeImageView setFrame:CGRectMake(0.0f,0.0f, 100.0f, 100.0f)];
/*調用 beginAnimations:context:方法來啟動一個動畫後,動畫並不會立即被執行,直到你調用 UIView 類的 commitAnimations 類方法。對一個視圖對象執行的介於 beginAnimations:context:方法跟 commitAnimations 方法之間的操作(例如移動)會在 commitAnimations 被執行後才會生效。
啟動一個動畫塊。任何在此類方法調用後你提交給視圖的動畫屬性的改變會在動畫提交後得到執行。
*/
[UIView beginAnimations:@"xcodeImageViewAnimation" context:self.xcodeImageView];
//設定動畫時間為5s
[UIView setAnimationDuration:5.0f];
//接受動畫代理
[UIView setAnimationDelegate:self];
//設定訊息發送到動畫代表當動畫停止。如果你指定一個動畫代表一個開始/提交動畫,你用這個方法來指定選取器被調用後,動畫結束。這種方法並沒有做任何事情如果調用外部的一個動畫塊。它必須被調用beginAnimations和commitAnimations方法之間。這個選取器預設設定為NULL。
[UIView setAnimationDidStopSelector:@selector(imageViewDidStop:finished:context:)];
/* 設定Frame在右下角 */
[self.xcodeImageView setFrame:CGRectMake(200.0f,350.0f,100.0f,100.0f)];
//提交動畫
[UIView commitAnimations];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImage *xcodeImage = [UIImage imageNamed:@"Xcode.png"];
self.xcodeImageView = [[UIImageView alloc] initWithImage:xcodeImage];
//設定圖片的Frame
[self.xcodeImageView setFrame:CGRectMake(0.0f,0.0f, 100.0f, 100.0f)];
self.view.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.xcodeImageView];
}
-(void) viewDidAppear:(BOOL)paramAnimated{
[super viewDidAppear:paramAnimated];
//從左上方開始
[self.xcodeImageView setFrame:CGRectMake(0.0f,0.0f, 100.0f, 100.0f)];
/*調用 beginAnimations:context:方法來啟動一個動畫後,動畫並不會立即被執行,直到你調用 UIView 類的 commitAnimations 類方法。對一個視圖對象執行的介於 beginAnimations:context:方法跟 commitAnimations 方法之間的操作(例如移動)會在 commitAnimations 被執行後才會生效。
啟動一個動畫塊。任何在此類方法調用後你提交給視圖的動畫屬性的改變會在動畫提交後得到執行。
*/
[UIView beginAnimations:@"xcodeImageViewAnimation" context:self.xcodeImageView];
//設定動畫時間為5s
[UIView setAnimationDuration:5.0f];
//接受動畫代理
[UIView setAnimationDelegate:self];
//設定訊息發送到動畫代表當動畫停止。如果你指定一個動畫代表一個開始/提交動畫,你用這個方法來指定選取器被調用後,動畫結束。這種方法並沒有做任何事情如果調用外部的一個動畫塊。它必須被調用beginAnimations和commitAnimations方法之間。這個選取器預設設定為NULL。
[UIView setAnimationDidStopSelector:@selector(imageViewDidStop:finished:context:)];
/* 設定Frame在右下角 */
[self.xcodeImageView setFrame:CGRectMake(200.0f,350.0f,100.0f,100.0f)];
//提交動畫
[UIView commitAnimations];
}
運行結果
運動後結果