UIAlertView(ダイアログ)
確認や, 選択などに利用するダイアログを表示させるUIAlertViewについてです
方式
利用用途とコードの書き方は2つあります
- 確認のためのダイアログ(メッセージやエラーなど)後処理が必要ない
- 選択などで後処理が必要
簡単に区分けすると,
後処理が必要ない場合
ダイアログを表示するためのコードを書きます
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Hello" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alert show];
“OK”ボタンをひとつ用意しました
これは表示, 確認のためだけで選択もなければ後処理もありません
後処理が必要な場合
ダイアログを表示するだけでなく, UIAlertViewDelegateの, -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndexを実装します。そして
, UIAlertViewのインスタンスにひもづけます
ダイアログの表示
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Delete Message" message:@"Do you want to delete?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"OK", nil]; [alert show];
先ほどと違うのは, delegateを指定していることと, cancelButton, otherButtonに名前を入れていることです
これでボタン2つになります。さらに必要な場合は, otherButtonTitlesのところに追加します
次はボタンごとの処理を実装します, UIAlertViewDelegate の実装です
後処理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { switch (buttonIndex) { case 0: NSLog(@"Cancel delete"); break; case 1: NSLog(@"Yes delete it"); [self closePopup]; break; default: break; } }
ボタンインデックスごとに処理を書きます。Cancelが0です。ボタンを増やせばインデックスは増えます。