LoginSignup
54
54

More than 5 years have passed since last update.

[Swift]ストーリーボードでポップアップビューを実装

Posted at

PopUpVewSample.gif

iOSでポップアップビューの自作を行う。
iOSでポップアップビューを実装する(with Storyboard)

こちらの記事を参考にしてストーリーボードを使ってポップアップビューを自作。
上記の記事でも言及されているが、世の中には高機能でオシャレなポップアップ/モーダル実装がたくさんあるので、まずはそれらを採用できないか検討するのが賢明かと思われます。

Deployment Target:iOS 8.0
Swift:2.2

ViewControllerを2つ

最初のViewControllerとポップアップのViewControllerの2つを用意。

Main_storyboard_—_Edited3.png

ポップアップのViewController

背景透過で後ろの画面を表示させるためにポップアップのViewControllerのPresentationをOver Current Contextに設定

Main_storyboard_—_Edited_と__Swift_ストーリーボードでポップアップビューを実装あ.png

背景透過のView

ポップアップは背景透過のViewの上にポップアップ(ピンク)のView重ねて実現する。
背景透過はBackgroundに透過カラーを設定する。
ここでAlphaの設定を変えてしまうと、そのviewのsubviewsもAlphaの影響を受けてしまうのでAlphaは1のまま。
ポップアップ以外の場所(背景透過の部分)をタップした時にポップアップを閉じる処理をしたいのでViewを識別するTagに1を設定する。

Main_storyboard_—_Edited_と_1__zsh_と__Swift_ストーリーボードでポップアップビューを実装_と_Kobito.png

ポップアップView

背景透過Viewと区別するため、Tagに2を設定する。
Main_storyboard_—_Edited5.png

セグエで接続

最初のViewControllerとポップアップのViewControllerをセグエに接続。
TransitionCrosse Dissolveを設定。
ここらへんをもっとポップアップぽくしたい時は、カスタムクラスなどで実装する。

Main_storyboard_—_Edited4.png

ポップアップを閉じる

ポップアップのViewControllerでCloseボタンをタップ、またはポップアップ以外の場所(背景透過の部分)をタップした時にポップアップを閉じる処理を入れる

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesEnded(touches, withEvent: event)
    for touch: UITouch in touches {
        let tag = touch.view!.tag
        if tag == 1 {
            dismissViewControllerAnimated(true, completion: nil)
        }
    }
}

@IBAction func didTapClose(sender: AnyObject) {
    dismissViewControllerAnimated(true, completion: nil)
}

サンプルコード

54
54
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
54
54