3

次のように作成されたViewControllerインスタンスがありますinstantiateViewControllerWithIdentifier

TBSCTestController* testController = [self.storyboard instantiateViewControllerWithIdentifier: @"OTP"];

TBSCTestControllerストーリーボードのラベルに接続されているという名前のIBOutletプロパティがあります。label

IBOutletアルベル

labelこのコードを使用するテキストを変更したいのですが、何も変更されません。

testController.label.text = @"newText";
[self.view addSubview: testController.view];  

testController有効なインスタンスですが、labelはnilです。私は何を取りこぼしたか?

4

1 に答える 1

9

コントローラUILabelnilインスタンス化したが、ビューがロードされなかったためです。コントローラのビュー階層は、そのビューへのアクセスを最初に要求したときにロードされます。したがって、@ lnafzigerが提案したように(この正確な理由で重要になるはずですが)、2行を切り替えると機能します。それで:

[self.view addSubview: testController.view];  
testController.label.text = @"newText";

この点を説明する例として、これでも機能します。

// Just an example. There is no need to do it like this...
UIView *aView = testController.view;
testController.label.text = @"newText";
[self.view addSubview: testController.view];  

またはこれ:

[testController loadView];
testController.label.text = @"newText";
[self.view addSubview: testController.view];  
于 2012-05-28T07:47:47.863 に答える