なんとかするから、なんとかなる

エンジニア関係のことを書きます

iOS UIViewControllerのPresentに対してカスタムアニメーションをつけたらブラックアウトしたときの対処法

English Version below

はじめに

UIViewControllerのモーダル表示presentメソッドに独自アニメーションをつけたら、dismiss時に画面が黒くなった(ブラックアウトした)ときの対処方法です。

UIViewControllerでモーダル表示時にアニメーションを指定するときに次のようなコードを書いていました。

  • **ViewController
func transtionView() {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let myVC = storyboard.instantiateViewController(withIdentifier: "MyVC")    
    myVC.transitioningDelegate = self
    myVC.modalTransitionStyle = .cutom //ここ
    self.present(myVC, animation: true)
}

extension ViewController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return MyPresentAnimation()
    }

    func animationController(forDismissed: UIViewController) ->  UIViewControllerAnimatedTransitioning?
        return MyDismissAnimation()
    }

このようなコードを実行したとき、presentで遷移したときはうまく行っているように見えました。

しかし、dismissで戻ってきたとき、animationが完了後に画面がブラックアウトしました。

UIWindow以外なくなりました。おそらくrootViewControllerがなくなりました。

解決方法

コードのコメントにも書いてあるとおり、myVC.modalTransitionSytleの行をコメントアウトすると正常に遷移しました。

具体的な原因はわかりませんが、おそらくmodalTransitionStyle = .customを指定した場合、 UIViewControllerTransitioningDelegate の以下のメソッドを実装しなければいけない気がします。(試せていないです)

func presentationController(forPresented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?

最後に

原因がわからなくて半日くらい頭を抱えていました。

アニメーションの部分はかなり多様する機能なので、もっと勉強しようと心に決意。

そのうち、アニメーション付与の方法についても紹介したいと思います。