モーダルビューコントローラーを提示しています。そのモーダルView ControllerのviewDidLoad
では、親VCへの参照が見つからないようです.... parentViewController
、presentingViewController
など。これがまだ設定されていない場合、どうすれば参照を取得できますか?
2 に答える
weak
一般的な解決策として、最初のビュー コントローラーへのポインターである 2 番目のコントローラーに独自のプロパティを設定できます。最初のコントローラは、最初のセグエで 2 番目のコントローラのプロパティを設定する必要がありprepareForSegue
ます。
あなたの質問への答えとして、parentViewController
View Controllerのコンテインメントを使用している場合にのみ設定されます(これは行っていません)。を実行するpresentingViewController
と が設定されますがpresentViewController
、最初のビュー コントローラーがナビゲーション コントローラーに埋め込まれているかどうかによって動作が変わります (埋め込まれている場合は 2 番目のビュー コントローラーpresentingViewController
がナビゲーション コントローラーであり、そうでない場合はビュー コントローラーです)。であると予想されます)。presentingViewController
すると、まったく設定されていないように見えますpushViewController
。
要するに、最初のコントローラーで 2 番目のコントローラーのカスタム プロパティを設定すると、はるかに信頼性と一貫性が高くなることがわかりましたprepareForSegue
。
したがって、 には、次のようなSecondViewController
.hがあります。@interface
@class FirstViewController;
@interface SecondViewController : UIViewController
@property (nonatomic, weak) FirstViewController *firstViewController;
@end
そして、最初のView Controllerには、prepareForSegue
次のようなものがあります。
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"IdentifierForSegueToSecondControllerHere"])
{
SecondViewController *controller = segue.destinationViewController;
controller.firstViewController = self;
}
}
明らかに、ストーリーボードを使用している場合は、上記の点が当てはまります。NIB を使用している場合は、次のようにします。
SecondViewController *controller = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
controller.firstViewController = self;
[self presentViewController:controller animated:YES completion:nil];
とにかく、 でそのfirstViewController
プロパティを設定すると、次のような のプロパティにアクセスしたり、 のパブリック メソッドを呼び出したりできるようSecondViewController
になります。SecondViewController
FirstViewController
// up at the top, where you have your import statements, include the following
#import "FirstViewController.h"
// then, in the @implementation of the SecondViewController, you can reference
// the first view controller and its properties, such as:
self.firstViewController.someStringProperty = @"some value";
概念的に言えば、ビューはいつでもロードできます。ビューが読み込まれたからといって、何らかの形で表示されるとは限りません。
表示中のView Controllerを発見できる最も早い時点は、のviewWillAppear:
メソッドにありUIViewController
ます。