UIAlertView
UIAlertViewはアラートを表示させる時に使用します。
アラートはユーザに注意を促したり、処理の結果を通知したりしたい時に使用します。

UIAlertViewのクラス階層
生成
// 生成例
UIAlertView *alert = [[UIAlertView alloc] init];
// 生成と同時に各種設定も完了させる例
UIAlertView *alert =
[[UIAlertView alloc]
initWithTitle@"タイトル"
message:@"メッセージ"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil
];
| 引数 | 設定する値 |
|---|---|
| initWithTitle | アラートのタイトル |
| message | アラートのメッセージ |
| delegate | デリゲート(不要の場合はnil) |
| cancelButtonTitle | キャンセルボタンの表示名 |
| otherButtonTitles | 確認ボタンの表示名 |
UIAlertViewのプロパティ
| プロパティ名/型 | 読専 | 説明 |
|---|---|---|
| delegate (UIAlertViewDelegate) |
デリゲートを指定する (例)alert.delegate = self; |
|
| title (NSString) |
タイトルを指定する (例)alert.title = @"確認"; |
|
| message (NSString) |
メッセージを指定する (例)alert.message = @"実行してもよろしいですか?"; |
|
| cancelButtonIndex (NSInteger) |
キャンセルボタンの位置を指定する(0から) (例)2つめのボタンをキャンセルボタンに設定する alert.cancelButtonIndex = 1; |
|
| numberOfButtons (NSInteger) |
○ | ボタンの数を取得する (例)int cnt = alert.numberOfButtons; |
主要なプロパティのみ掲載しています。
上記「UIAlertViewのクラス階層」にあるクラスのプロパティも使用できます。
UIAlertViewのメソッド
| メソッド名 | 説明 |
|---|---|
| -(NSInteger)addButtonWithTitle: (NSString *)title |
ボタンを追加する (例)[alert addButtonWithTitle:@"ほげ"]; |
| -(void)show | アラートを表示する (例)[alert show]; |
主要なメソッドのみ掲載しています。
上記「UIAlertViewのクラス階層」にあるクラスのメソッドも使用できます。
UIAlertViewのデリゲートメソッド
| メソッド名 | 説明 |
|---|---|
| -(void)alertView: (UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex |
ボタンがタップされた時に呼び出される ※buttonIndexにボタン番号が渡されてくる |
| -(void)willPresentAlertView:(UIAlertView*)alertView | アラート表示直前に呼び出される |
| -(void)didPresentAlertView:(UIAlertView*)alertView | アラート表示直後に呼び出される |
主要なデリゲートメソッドのみ掲載しています。
UIAlertViewの使用例
// 1行で書くタイプ(1ボタンタイプ)
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle:@"お知らせ" message:@"完了しました"
delegate:self cancelButtonTitle:@"確認" otherButtonTitles:nil];
[alert show];
// 1行で書くタイプ(複数ボタンタイプ)
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle:@"確認" message:@"削除してもよろしいですか?"
delegate:self cancelButtonTitle:@"いいえ" otherButtonTitles:@"はい", nil];
[alert show];
// 複数行で書くタイプ(1ボタンタイプ)
UIAlertView *alert = [[UIAlertView alloc] init];
alert.title = @"お知らせ";
alert.message = @"完了しました";
[alert addButtonWithTitle:@"確認"];
[alert show];
// 複数行で書くタイプ(複数ボタンタイプ)
UIAlertView *alert = [[UIAlertView alloc] init];
alert.delegate = self;
alert.title = @"確認";
alert.message = @"実行してもよろしいですか?";
[alert addButtonWithTitle:@"いいえ"];
[alert addButtonWithTitle:@"はい"];
[alert show];
// アラートのボタンが押された時に呼ばれるデリゲート例文
-(void)alertView:(UIAlertView*)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 0:
//1番目のボタンが押されたときの処理を記述する
break;
case 1:
//2番目のボタンが押されたときの処理を記述する
break;
}
}

