2011年11月10日木曜日

iOS5のpresentingViewController

photo-12 by tubes.
photo-12, a photo by tubes. on Flickr.
iOS 5 で UIImagePickerController を使用して、カメラUIを表示させるまでは良かったのですが、これが消せないという問題に遭遇しました。

「iOS カメラプログラミングトピックス」という Apple のドキュメントを参考にしていたのですが、例えば、カメラUIをキャンセルした時のコードは以下のような感じになっています。
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
 [[picker parentViewController] dismissModalViewControllerAnimated:YES];
 [picker release];
}
しかし iOS 5 では、これだとうまく動きません。
[picker parentViewController] からは nil が返ってくるからです。

途方に暮れた中、見つけたのが以下。
UIViewController Class Reference の parentViewController を見るとこんな記述が…。
Prior to iOS 5.0, if a view did not have a parent view controller and was being presented modally, the view controller that was presenting it would be returned. This is no longer the case. You can get the presenting view controller using the presentingViewController property.
要するに iOS 5 からは、モーダルビューの親は parentViewController ではなく、
presentingViewController で参照せよ、ということらしいです。
メソッドの名前からして、「もう俺を親と呼ぶな」と言っているみたいですが(笑)、いや、笑えないんですが、これからあなたを何と呼べばいいんでしょう? プレゼンしてくれてるビューコントローラーさん?

よって、iOS 5 からは、以下のように記述するのが正解のようです。
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
 // iOS5からこちらを使わないとダメ!
 [[picker presentingViewController] dismissModalViewControllerAnimated:YES];
 [picker release];
}

まだちょっと続きまして、
実は以下のようにしてもうまく動いてしまいます。
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
 // 実はこれでもうまく動く。
 [picker dismissModalViewControllerAnimated:YES];
 [picker release];
}
この辺りは、混乱要因だと思うんですけど、、、
UIViewController Class Reference の dismissModalViewControllerAnimated: メソッドの説明の中に、以下のような記述があります。
If you call this method on the modal view controller itself, however, the modal view controller automatically forwards the message to its parent view controller.
これによると、モーダルビューコントローラー自身に dismissModalViewControllerAnimated: メソッドを送信すると、自動的に親ビューコントローラーにメッセージを転送するよと書いてあります。しかも、ここではまだ「親」(parent view controller)と言っていますね。
推測ですが、iOS 5 では内部で presentingViewController にメッセージを転送しているのではないかと思います。

0 件のコメント:

コメントを投稿

Related Posts Plugin for WordPress, Blogger...