UIAlertViewでとまどったこと…その1
これは「Touch Touch Shapes」制作中に「ん?」となったお話です。
UIViewの継承クラスに下記のコードを実装。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AlertTest" message:@"Test" delegate:self cancelButtonTitle:@"Button1" otherButtonTitles:@"Button2", @"Button3", nil]; [alert show]; [alert release]; } - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSLog(@"clickedButtonAtIndex"); NSLog(@"buttonIndex:%d", buttonIndex); }
そして、ビルド&実行。画面にタッチするとアラートが表示されます。
…しかし、アラートを表示している時にiPhoneのホームボタンを押すとデバッガコンソール上にこのような文字が!
clickedButtonAtIndex
buttonIndex:0
つまりUIAlertViewにキャンセルボタンを設定すると
アラート表示時にホームボタンを押した場合 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex が呼び出される
ということになります。
何が困るのか
ホームボタンを押すとアプリは終了するので特に問題ないのでは?という考えもありますが、私は当初こんなコードを実装してしまい問題が起こりました。
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 0) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://monobyte.jp/iphone/"]]; } }
つまり…
- アラートを表示する
- ホームボタンを押してアプリを終了する
- アプリが終了した瞬間、Safariが起動
という動作になります。実装内容によっては問題が起こってしまうわけですね。
解決方法
アラートを表示中にホームボタンを押してもalertViewが呼び出されないようにするには次の方法があります。
- 1) キャンセルボタンを設定しない
- キャンセルボタンが設定されていない場合はalertViewは呼び出されないようです。
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AlertTest" message:@"Test" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Button1", @"Button2", @"Button3", nil];
- 2) - (void)alertViewCancel
- (UIAlertView*)alertViewを実装する:ホームボタンを押すと、alertViewの代わりにalertViewCancelが呼び出されるようになります。これは上記(1)を併用しても同様の動作となります。
- (void)alertViewCancel:(UIAlertView*)alertView { NSLog(@"cancel"); }
アラート表示して何らかの処理を行う必要がある場合などを考えると*1、alertViewCancelを実装して、その中に必要な処理を実装するという方法がオススメかもしれません。
「Touch Touch Shapes」制作時はOS2.2で動作確認を行いましたが、この動作はOS3.0でも変わっていませんでした。
「UIAlertViewでとまどったこと…その2」へ続きます。。。
*1:データの保存など。