LoginSignup
16
24

More than 5 years have passed since last update.

iOS(Swift)でアラート画面のようにViewの背景透過をする

Last updated at Posted at 2017-03-01

アラート画面をカスタマイズしたい

コードはgithubに上げておきました。
要はvc.modalPresentationStyle = .overCurrentContextをつけるだけと言う感じです。

イメージ

アラート画面をカスタムする時、背景透過をするのに地味に時間がかかったのでメモ。

modal.gif

遷移元の実装

Storyboardをつかってやってみます。

遷移元のViewControllerは、アラート画面を表示した時に背景透過が確認できるように、適当な背景画像を差し込んでおきます。中央に開くボタンを設置しておいてViewControllerと繋いでおきます。

Screen Shot 2017-03-01 at 16.47.08.png

遷移元のViewController.swift

import UIKit

class ViewController: UIViewController {
    ////

    // StoryboardとUIButtonをつなぎます
    @IBAction func openAction(_ sender: Any) {
        let sb = UIStoryboard(name: "Modal", bundle: nil)
        let vc = sb.instantiateInitialViewController() as! ModalViewController
        // 背景が真っ黒にならなくなる
        vc.modalPresentationStyle = .overCurrentContext

        present(vc, animated: false)
    }

}

遷移先の実装

遷移先のViewControllerは以下のようにStoryboardで設定しておきます。 UIView を差し込んでその中に UILabelUIButton (cancel用)を入れました。ViewControllerのViewの背景色を画像のようにします。

Screen Shot 2017-03-01 at 16.48.14.png

遷移先のViewController.swift

import UIKit

class ModalViewController: UIViewController {
    ////

    // StoryboardとUIButtonをつなぎます
    @IBAction func cancelAction(_ sender: Any) {
        dismiss(animated: false)
    }

}

アラートの角を丸める

これだけだと表示したアラート画面の角が丸くなっていないので丸めます。Storyboardできるので設定します。
layer.cornerRadiusNumber を設定。
layer.masksToBoundstrue にします。

Screen Shot 2017-03-01 at 17.06.png

あとは遷移先のViewをいじるだけです。

16
24
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
16
24