LoginSignup
9
10

More than 5 years have passed since last update.

AutoLayout でレイアウトした コンテナ ViewController 内の ViewController をアニメーションして入れ替える

Posted at

そもそも Container View Controlloer を設定する方法は下記を参考に。
カスタムContainer View Controllerを作る

下記は AutoLayout で実行した例。ただしアニメーション開始位置だけは簡便のため frame を使っている。

    func transientToViewController(newMainVC : UIViewController ){
        let currentVC = self.currentVC // この例ではインスタンス変数で保持しています。もしくは引数で渡したりしてください。
        currentVC.willMoveToParentViewController(nil)
        self.addChildViewController(newMainVC)
        self.view.addSubview(newMainVC.view)

        // アニメーション開始前の初期位置を設定 ここでは上部からスライドするように設定
        let width = currentVC.view.bounds.size.width
        let height = currentVC.view.bounds.size.height
        newMainVC.view.frame = CGRectMake(0 , -height ,width,height)

        self.transitionFromViewController(
            currentVC,
            toViewController: newMainVC,
            duration: 0.25,
            options: [ UIViewAnimationOptions.TransitionNone ], // ここのオプションを変えると紙をめくるようなエフェクトになったりする
            animations: {
                self.rebuildConstraints() // 最終的なレイアウトを行う
                self.view.layoutIfNeeded() // **これ重要** これがないとアニメーションしない
            },
            completion: { (success : Bool) in
                currentVC.view.removeFromSuperview()
                currentVC.removeFromParentViewController()
                self.prevViewController = currentVC

        })

    }

AutoLayout で やるには animations の中で layoutIfNeeded を呼び出さないとアニメーションしないことに気がつかなくて結構はまった。

9
10
0

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
9
10