您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發筆記:用 animateWithDuration 控制頁面進出效果

編輯:iOS 開發綜合

最近研究了一些頁面進出的動畫效果,主要使用 UIView 的 animateWithDuration 方法。當然,早期的 beginAnimations 也能達到同樣效果。以下記錄幾種常見做法。

例一:從螢幕下方漸漸彈出

先把 view 的 center 設到螢幕下方(畫面外),再動畫移動到目標位置:

-(void)fadeIn {
    CGRect rect = [[UIScreen mainScreen] bounds];
    self.view.center = CGPointMake(rect.size.width / 2, 720);
    [UIView animateWithDuration:0.5f animations:^{
        self.view.center = CGPointMake(rect.size.width / 2, 240 + 10);
    } completion:^(BOOL finished) {
        // 動畫完成後要做的事
    }];
}

例二:再漸漸退回下方

-(void)fadeOut {
    CGRect rect = [[UIScreen mainScreen] bounds];
    [UIView animateWithDuration:0.5f animations:^{
        self.view.center = CGPointMake(rect.size.width / 2, 720);
    } completion:^(BOOL finished) {
        [imageView cancelImageLoad];
        [imageView release];
    }];
}

舊寫法:beginAnimations

如果用舊的 beginAnimations,寫法如下:

CGRect rect = [[UIScreen mainScreen] bounds];
self.myimg.center = CGPointMake(rect.size.width / 2, 720);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
self.myimg.center = CGPointMake(rect.size.width / 2, 720);
[UIView commitAnimations];

掌握的核心觀念其實很簡單:只要設定 center 座標,動畫就會把 view 從目前位置平滑移動到新位置。

可以做動畫的屬性

下列屬性都能放進動畫區塊中做出轉場效果:

  • frame
  • bounds
  • center
  • transform
  • alpha
  • backgroundColor
  • contentStretch

例:一個淡出、另一個淡入

[UIView animateWithDuration:1.0 animations:^{
    firstView.alpha = 0.0;
    secondView.alpha = 1.0;
}];

參數補充:completion 是動畫執行完畢後要執行的區塊;options 是動畫執行的選項(如節奏曲線);delay 是動畫開始前的等待時間。相較之下,animateWithDuration 的 block 寫法比舊的 beginAnimations/commitAnimations 更直覺、更易讀,是新專案的首選。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved