【swift】ポップアップ・アラートの簡単実装方法【UIAlertController】

iOSアプリ開発

ポップアップ・アラートを実装するには「UIAlertController」を使うと楽でいい感じ。

ガッチガチにカスタムしたオリジナルのポップアップ・アラートを作るならストーリーボードでUIView作った方がいいですが、OKとキャンセルだけの簡単なポップアップ・アラートであれば「UIAlertController」で十分です。

【必須】まずはポップアップ・アラートの元を用意する。

まずはポップアップ・アラートの元を用意します。

let alert: UIAlertController = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle:  .alert)

以降のソースコードは、ポップアップ・アラートに表示させたい内容によって選択する。

OK・キャンセルのポップアップ・アラート

let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{(action: UIAlertAction!) -> Void in
//OKボタンを押した時の処理
})

let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertActionStyle.cancel, handler:{(action: UIAlertAction!) -> Void in
//キャンセルボタンを押した時の処理
})

alert.addAction(cancelAction)
alert.addAction(defaultAction)

テキストフィールドのポップアップ・アラート

alert.addTextField( configurationHandler: { (user: UITextField!) -> Void in

})

【必須】最後にポップアップ・アラートを生成する

ポップアップ・アラートの部品を記述したら、最後にpresentでポップアップ・アラートを生成しよう

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

Category
9WEB