Objective-C: アラートをあげる UIAlertView, UIAlertController
概要
タイトル通り単純明快。 アラートをあげる方法です。
こんな感じです。
詳細
コードは、以下の通りです。あ、キャンセル側に「OK」という文字列をアサインしているひねくれた例なのでご注意を。
- (IBAction)PushButton:(id)sender { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"タイトル" message:@"メッセージそのもの" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"開く", nil]; [alert show]; } - (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { switch (buttonIndex) { case 0: [self cancelButton]; break; case 1: [self otherButton]; break; } } - (void)cancelButton { NSLog(@"cancel"); } - (void)otherButton { NSLog(@"other"); }
とまぁ、ここまで書いて思い出しました。昨今、このやり方は古いっすってXcodeさんに警告されることを... でも、古いiOSもサポートするなら使うんでしょ?っていまさらiOS7とかないか。
今からの人は、こちら
で、ついでなので、新しい方も書いてみます。
いや、正確に表現しておきます「コピペしてみました」ですね。
- (IBAction)PushButton:(id)sender { UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"タイトル" message:@"メッセージ" preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:[UIAlertAction actionWithTitle:@"はい" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { [self yesButtonPushed]; }]]; [alertController addAction:[UIAlertAction actionWithTitle:@"いいえ" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { // cancelボタンが押された時の処理 [self noButtonPushed]; }]]; [self presentViewController:alertController animated:YES completion:nil]; } - (void)yesButtonPushed { NSLog(@"はい"); } - (void)noButtonPushed { NSLog(@"いいえ"); }
概要の画面ショットは、このサンプルを動かしたときにキャプチャしたものです。
まとめ
なんで、こういうのって変えるんですかね? そして、変えるにしても古いのと新しいので両方面倒みるのが、下々の者っていうのも若干納得がいかないです。
まぁ、コピペするならあんまり関係ないけど。