酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

iOSでUIViewのアニメーション処理をBlocksで書いてみた

iOS 3.x系との下位互換を気にしないといけないアプリケーションばかり開発していたので、当然Blocksを使う機会がありませんでした。少し勉強がてらにBlocksでアニメーション処理を書いてみました。(スキル的にお察しの通り)高度なことはできませんので、簡単なフェードイン・フェードアウトのアニメーション処理を書いてみました。

- (void) showLabel:(id)sender {
    // アニメーションでラベルを表示させる
    void (^animations)(void) = ^{ 
        self.messageLabel.alpha = 1.0;
    };
    void (^completionAnimation)(BOOL) = ^(BOOL finished) {
        // 2秒後に表示させたラベルをアニメーションさせながら消す
        [self performSelector:@selector(unshowLabel) withObject:nil afterDelay:2.0];
    };
    
    self.messageLabel.alpha = 0.0;
    self.messageLabel.hidden = NO;
    [UIView animateWithDuration:0.5 animations:animations completion:completionAnimation];
}

performSelectorで2秒後に以下のラベルを非表示にするメソッドが実行される。

- (void) unshowLabel {
    // アニメーションでラベルを非表示にする
    void (^animations)(void) = ^{ 
        self.messageLabel.alpha = 0.0;
    };
    void (^completionAnimation)(BOOL) = ^(BOOL finished) {
        self.messageLabel.hidden = NO;
    };
    [UIView animateWithDuration:0.5 animations:animations completion:completionAnimation];
}