swift alertを表示
こんなのを作ります。
ポイント
1- UIAlertControllerがベースとなるコントローラー
画面の大枠と考えると良い
2- UIAlertControllerにUIAlertActionでアクション(選択肢)を追加していく
userの反応を待つので、クロージャーを利用する クロージャーは、値が入るまで(ユーザーの反応が決定されるまで)実行されない。
3-present で表示してあげる
@IBAction func myAlert(_ sender: Any) { //まず外枠のインスタンスをつくる let alertController = UIAlertController(title: "alert desu", message: "are you sure?", preferredStyle: .alert) //内側のokボタンを作成 クロージャー alertController.addAction(UIAlertAction(title: "ok", style: .default, handler: { (action) in print("pk pushed") self.dismiss(animated: true, completion: nil) })) //内側のcancelボタンを作成 styleが cancelになる alertController.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: {(action) in print("cancel pushed") self.dismiss(animated: true, completion: nil)})) //ここで表示してあげてる self.present(alertController, animated: true, completion: nil) }