カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

アラートを表示する UIAlertController

この記事は最終更新日から1年以上経過しています。

アラートを表示するにはUIAlertControllerを利用します。

アラート(ダイアログ)を表示する

タイトルとメッセージを設定し、アラートのオブジェクトを作成します。

let aTitle = "タイトル"
let aMessage = "メッセージ表示"

let alert = UIAlertController(title: aTitle, message: aMessage, preferredStyle: .alert)

OKボタンを作成します。

alert.addAction(
    UIAlertAction(title: "OK", style: .default, handler: { action in
        print("OKをタップした場合の処理")
    })
)

キャンセルボタンを作成します。
処理は何もしないので、handlerはnilで大丈夫です。

alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))

アラートを表示する

self.present(alert, animated: false, completion: nil)

ActionSheetを表示する

ActionSheetは下から出てくるパターンです。
選択式にして使ったりしますね。

先ほどと同じく、タイトルとメッセージを設定し、アラートのオブジェクトを作成します。
preferredStyleに.actionSheetを指定します。

let aTitle = "タイトル"
let aMessage = "メッセージ表示"

let alert = UIAlertController(title: aTitle, message: nil, preferredStyle: .actionSheet)

ここで注意点!
iPadでは次のコードを書かないとクラッシュします。
iPadの場合はActionSheetが任意の場所に表示されますので、親ビューの設定と位置・サイズが必要になります。
(サイズは0でも大丈夫なようです)
sourceViewとsourceRectが必須ですので忘れないようにしましょう。

alert.popoverPresentationController?.sourceView = self.view
alert.popoverPresentationController?.sourceRect =
    CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height, width: 0, height: 0)
alert.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.any

選択式のボタンとキャンセルボタンを作成します。

alert.addAction(
    UIAlertAction(title: "選択肢1", style: .default, handler: { action in
        print("選択肢1が選択されました。")
    })
)

alert.addAction(
    UIAlertAction(title: "選択肢2", style: .destructive, handler: { action in
        print("選択肢2が選択されました。")
    })
)

alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))

最後にアラートを表示します。

self.present(alert, animated: true, completion: nil)

Xcode: 8.3.2
Swift: 3.1
OS: Sierra 10.12

この記事がお役に立ちましたらシェアお願いします
3,384 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です