AutoLayoutがオンの状態でのアニメーション処理の書き方

AutoLayoutをオンにした状態だと、以下のようなアニメーションの処理が動かないというのを知らなかった 汗

[UIView animateWithDuration:1.0f
                      delay:0.0f
                    options:UIViewAnimationOptionCurveEaseOut
                 animations:^{
                     _btnTest.y = 200;
                 }
                 completion:^(BOOL finished) {
                     //
                 }];

まあ理屈から考えるとその通りであって、で今後は(まあこれまでもそうかもだけど)iPhone6 plusみたいなものも出てきたのでAutoLayoutはこれまで以上に必須だと思うので、AutoLayoutにおけるアニメーションの書き方を勉強しておく。

参考サイト:
ios - AutoLayout, Constraints and Animation - Stack Overflow

どんなのやりたいかというと、たとえばTumblr

f:id:ushisantoasobu:20140921014548p:plain

のタブ中央の鉛筆アイコンをタップしたときに

f:id:ushisantoasobu:20140921014634p:plain

の6つのメニューボタンが下から飛び出るようなアニメーションででてくるんだけど、それをAutoLayoutがオンの状態でどうやってやるか。

サンプルコードはgithubに。

ushisantoasobu/TestAnimationInAutoLayout · GitHub

ポイントとしては以下のところ。

//1. 制約を除外してあげる
[self.view removeConstraints:@[_constraintHoge]];

//2. アニメーション先の制約を設定する(ここでいうとbottomから-1000)
_constraintHoge = [NSLayoutConstraint constraintWithItem:self.view
                                               attribute:NSLayoutAttributeBottom
                                               relatedBy:0
                                                  toItem:_btnHoge
                                               attribute:NSLayoutAttributeBottom
                                              multiplier:1
                                                constant:-1000];

//3. 2で設定した制約を追加してあげる
[self.view addConstraint:_constraintHoge];

//4. 以下のような書き方でアニメーションされる(layoutIfNeededがミソ)
[UIView animateWithDuration:1.0f delay:0.0 options:0 animations:^{
    [self.view layoutIfNeeded];
} completion:^(BOOL finished) {
    //
}];

書きながらいろいろサイトみてたらいくらでも記事あったな、、、