简体   繁体   English

如何访问从故事板加载的视图控制器的属性?

[英]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有一个名为labelIBOutlet属性,它与故事板中的标签TBSCTestController

IB奥特莱斯

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.

相关问题 如何在加载后从视图访问属性 - How to access properties from view after it loaded 如何从视图控制器移动到其他视图控制器在故事板编程 - How to move from a view controller into other view controller in storyboard programmatically Xcode:如何访问使用情节提要呈现的View Controller实例? - Xcode: How To Access The Instance Of A View Controller Presented Using Storyboard? 如何在UIView类中访问视图控制器的属性 - how to access properties of view controller in UIView class MVYMenuViewController:如何销毁从情节提要中实例化的视图控制器 - MVYMenuViewController: How to destroy a view controller which was instantiated from storyboard 如何从现有的视图控制器构建导航控制器? - How to build navigation controller from existing view controllers drew in storyboard? Xamarin iOS:如何将故事板中的视图连接到控制器? - Xamarin iOS: How to connect a view from a storyboard to a controller? 如何以编程方式从一个情节提要中的一个视图控制器转到另一个情节提要中的另一个视图控制器? - How to go from one view controller in One storyboard to another viewcontroller in another storyboard programmatically? 故事板:从子视图弹出到根视图控制器 - Storyboard : Pop to root view controller from subview 从情节提要中获取视图控制器堆栈 - get view controller stack from storyboard
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM