iPhone(iPad)アプリでAlertを表示するには、UIAlertViewを使います。delegateを設定することで、ボタンが押されたタイミングで処理を実行したり、押されたボタンによって処理を切り替えることができます。
OKボタンだけのアラート
ボタンが1つしかないアラートは以下のようにして表示します。
[[[UIAlertView alloc]
initWithTitle:nil
message:@"エラーが発生しました。"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil
] show];
initWithTitle:nil
message:@"エラーが発生しました。"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil
] show];
選択肢のあるアラート
ボタンを2つ以上表示する場合はdelegateを設定して、どのボタンが押されたのか判定します。
//以下の7行を実行するとアラートが表示される
[[[UIAlertView alloc]
initWithTitle:@"タイトル"
message:@"本当に実行しますか?"
delegate:self
cancelButtonTitle:@"キャンセル"
otherButtonTitles:@"実行する", nil
] show];
//ボタンを押したタイミングで以下のメソッドが実行される
-(void)alertView:(UIAlertView*)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 0){
//何もしない
}else{
[self doSomething];
}
}
[[[UIAlertView alloc]
initWithTitle:@"タイトル"
message:@"本当に実行しますか?"
delegate:self
cancelButtonTitle:@"キャンセル"
otherButtonTitles:@"実行する", nil
] show];
//ボタンを押したタイミングで以下のメソッドが実行される
-(void)alertView:(UIAlertView*)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 0){
//何もしない
}else{
[self doSomething];
}
}