LoginSignup
49

More than 5 years have passed since last update.

AutoLayout制約値を変更したアニメーションで勘違いしていた件

Last updated at Posted at 2015-05-28

@SatoTakeshiX さんの勉強会でAuto Layout の制約をいじったアニメーションについて教えてもらいました。
UIView.animations ブロックの中で制約の値変えたら良いのかと思ってたけど違うんですねー。完全に勘違いしてました。

制約を変えるのは animations ブロックの外。animatinosブロックの中では self.view.layoutIfNeeded を呼ぶのが正解。知らんかったわー。

  • ↓×これは間違い
[UIView animateWithDuration:0.3 animations:^{
    self.leftSpaceConstraint.constant = 430.f;
}];
  • ↓○これが正解
// (※1) 
[self.view layoutIfNeeded];

// 値の変更はアニメーションブロックの外!
self.leftSpaceConstraint.constant = 430.f; 

// アニメーション実行
[UIView animateWithDuration:0.3 animations:^{
    [self.view layoutIfNeeded]; // <-- ココ注目!
}];

※1【5/28追記】
@dokubeko さんからご指摘頂きました。
「制約を変更する前に一度layoutIfNeededを実行して未適用の表示を確実に更新しておくこと」とアップル公式のセッションビデオにあるとのことです。確かにー!
ご指摘ありがとうございます!

iOS開発会議は毎週木曜渋谷beezで開催中です。
ご興味ある方はぜひー!
https://www.facebook.com/groups/407821455988195/

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49