Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access properties of a view controller loaded from storyboard?

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:

IBOutlet albel

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?

like image 619
Fengzhong Li Avatar asked Dec 06 '25 07:12

Fengzhong Li


1 Answers

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];  
like image 163
Alladinian Avatar answered Dec 08 '25 20:12

Alladinian