タコさんブログ

プログラミングメモと小言

Auto LayoutのConstraintをアニメーションさせる

Auto Layoutを使用しているときに制約をアニメーションさせる方法

今回やるアニメーションは、ボタンを押したら下の位置にある緑色のヴュー(画面外)が

  • 表示されていないとき、ヴューが中央まで表示される
  • 表示されているとき、ヴューが下の位置に戻る

f:id:tiny_wing:20150102012407p:plain

レイアウト

  • ボタンを配置
  • Bottom Layout Guideの真下に緑色のヴュー(GreenView)を配置。このときの制約は [Bottom Layout Guide].top = [GreenView].top
  • GreenViewのサイズはとりあえず、[GreenView].width = [Superview].width、[GreenView].height = [Superview].height / 2 に設定

実装

まず、[Bottom Layout Guide].top = [GreenView].topとつけた制約にIBOutlet接続する。 後は、ボタンのクリックアクションで、この制約を更新して、UIView#animateWithDurationのanimationsブロックでview.layoutIfNeededを呼べば良い。

// 中央に移動
if constraint.constant == 0 {
    constraint.constant = self.view.frame.size.height / 2.0
} else {  // 下に移動
    constraint.constant = 0.0
}
        
let duration = 0.25
UIView.animateWithDuration(duration, animations: {
        self.view.layoutIfNeeded()
        }
)

ソースはこちら