Alertを表示する

iPhone(iPad)アプリでAlertを表示するには、UIAlertViewを使います。delegateを設定することで、ボタンが押されたタイミングで処理を実行したり、押されたボタンによって処理を切り替えることができます。

OKボタンだけのアラート

ボタンが1つしかないアラートは以下のようにして表示します。

[[[UIAlertView alloc]
  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];
  }
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">