更新时间:2023-02-12 13:01:20
您的 UILabel
nil
,因为您已经实例化了您的控制器,但它没有加载其视图。控制器的视图层次结构在您第一次请求访问其视图时加载。所以,正如@lnafziger建议(虽然应该重要的这个确切的原因)如果你切换两行它将工作。所以:
[self.view addSubview:testController.view];
testController.label.text = @newText;作为一个例子来说明这一点,即使这个也可以工作:
$ p> b
//只是一个例子。没有必要这样做...
UIView * aView = testController.view;
testController.label.text = @newText;
[self.view addSubview:testController.view];
或这一个:
[testController loadView];
testController.label.text = @newText;
[self.view addSubview:testController.view];
I have a view controller instance created with instantiateViewControllerWithIdentifier
like this:
TBSCTestController* testController = [self.storyboard instantiateViewControllerWithIdentifier: @"OTP"];
TBSCTestController
has an IBOutlet
property named label
which is hooked up with a label in the storyboard:
I want to modify the text of label
using this code but nothing changes:
testController.label.text = @"newText";
[self.view addSubview: testController.view];
The testController
is a valid instance but the label
is nil.
What did i miss?
Your UILabel
is nil
because you have instantiated your controller but it didn't load its view. The view hierarchy of the controller is loaded the first time you ask for access to its view. So, as @lnafziger suggested (though it should matter for this exact reason) if you switch the two lines it will work. So:
[self.view addSubview: testController.view];
testController.label.text = @"newText";
As an example to illustrate this point, even this one would work:
// 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];
Or this one:
[testController loadView];
testController.label.text = @"newText";
[self.view addSubview: testController.view];