[英]How to access properties of a view controller loaded from storyboard?
I have a view controller instance created with instantiateViewControllerWithIdentifier
like this:我有一个使用
instantiateViewControllerWithIdentifier
创建的视图控制器实例,如下所示:
TBSCTestController* testController = [self.storyboard instantiateViewControllerWithIdentifier: @"OTP"];
TBSCTestController
has an IBOutlet
property named label
which is hooked up with a label in the storyboard: TBSCTestController
有一个名为label
的IBOutlet
属性,它与故事板中的标签TBSCTestController
:
I want to modify the text of label
using this code but nothing changes:我想使用此代码修改
label
文本,但没有任何变化:
testController.label.text = @"newText";
[self.view addSubview: testController.view];
The testController
is a valid instance but the label
is nil. testController
是一个有效的实例,但label
为零。 What did i miss?我错过了什么?
Your UILabel
is nil
because you have instantiated your controller but it didn't load its view.你的
UILabel
nil
因为你已经实例化了你的控制器,但它没有加载它的视图。 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.
因此,正如@lnafziger 建议的那样(尽管出于这个确切原因它应该很重要),如果您切换两条线,它将起作用。 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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.