LoginSignup
44
46

More than 5 years have passed since last update.

【swift3.0/2.3】よく使う!モーダル表示まとめ【背景透明view】

Posted at

元の画面は見せつつメニューとか何かしらのviewを見せたいことってあるよね

こんな感じのやつ
※スタンプアプリをイメージ

modal_sample.gif

背景を透過させてモーダル表示をすれば良いんだけど、ちょっと注意が必要なのでメモとして残しておく

書き方(iOS8以上、swift2.3)

親からviewを呼び出すとき

let viewController = UIViewController()
viewController.modalPresentationStyle = .OverCurrentContext
viewController.view.backgroundColor = UIColor.clearColor()
presentViewController(viewController, animated: true, completion: nil)

viewを閉じるとき

dismissViewControllerAnimated(true, completion: {
        [presentingViewController] () -> Void in
            // 閉じた時に行いたい処理
            presentingViewController?.viewWillAppear(true)
})

注意点

  • presentViewControllerの前にmodalPresentationStyleとbackgroundColorをセットする
  • OverCurrentContextを使うと親のviewWillDisappearは呼ばれない
  • viewを閉じても親のviewWillAppearは呼ばれない

→要するにviewを閉じても呼び出した時の状態のまま親viewに戻る

上記は、閉じた時に親のviewWillAppearを呼ぶようライフサイクルを変更してみてます。
上記のようにしても今のところ不具合は確認できませんでしたが
閉じた時に何か処理をさせたい場合は、処理させたいメソッドを呼び出すようにするといいかも。

おまけ①

modalTransitionStyleを指定すると画面の切り替え方をカッコよくできます!!
分かりやすくまとまってるのでオススメ☆

おまけ②

swift3.0での書き方

親からviewを呼び出すとき

let viewController = UIViewController()
viewController.modalPresentationStyle = .overCurrentContext
viewController.view.backgroundColor = UIColor.clear
present(viewController, animated: true, completion: nil)

viewを閉じるとき

dismiss(animated: true, completion: {
        [presentingViewController] () -> Void in
            // 閉じた時に行いたい処理            
            presentingViewController?.viewWillAppear(true)
})

ちょっと短くなってスッキリ♪

「.OverCurrentContext」が3.0では「.overCurrentContext」になってた。
こんなのなかなか気付かないよねw

44
46
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
44
46