1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】アラートを表示する方法

Posted at

はじめに

Swiftでダイアログを表示したかったため、実装方法をまとめました。

基本的なダイアログの表示

UIAlertControllerのインスタンスを作成してpresent関数に渡すことで、ダイアログを表示することができる。
また、OKボタンのようなアクションを追加したい場合は、UIAlertActionのインスタンスを作成し、addActionでアラートに追加する。

let alert = UIAlertController(title: "タイトル", message: "サブタイトル", preferredStyle: .alert) 

// アクションの追加
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in 
	// アクションがタップされた時に実行される処理
	NSLog("OKがタップされました。")
}))
self.present(alert, animated: true, completion: nil)

Simulator Screen Shot - iPod touch (7th generation) - 2021-04-26 at 23.37.52.png

TextFieldを追加する

addTextFieldを使うことでダイアログにテキストフィールドを追加することができる。
(ただし、ダイアログにTextFieldを追加したい場合、preferredStyleプロパティをUIAlertController.Style.alertに設定する必要がある。)

let alert = UIAlertController(title: "タイトル", message: "サブタイトル", preferredStyle: .alert)

// TextFieldを追加
alert.addTextField { (textField) in
	// TextFieldの設定をする。
	textField.placeholder = "テキストを入力してください。"
}

// アクションの追加
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in 
	// アクションがタップされた時に実行される処理
	NSLog("OKがタップされました。")
}))
self.present(alert, animated: true, completion: nil)

Simulator Screen Shot - iPod touch (7th generation) - 2021-04-26 at 23.38.40.png

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?