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

半世苍凉 提交于 2019-12-30 07:10:08

问题


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?


回答1:


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];  


来源:https://stackoverflow.com/questions/10780289/how-to-access-properties-of-a-view-controller-loaded-from-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!