如何访问从storyboard加载的视图控制器的属性? [英] How to access properties of a view controller loaded from storyboard?

查看:130
本文介绍了如何访问从storyboard加载的视图控制器的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 instantiateViewControllerWithIdentifier 创建的视图控制器实例,如下所示:

  TBSCTestController * testController = [self.storyboard instantiateViewControllerWithIdentifier:@OTP]; 

TBSCTestController IBOutlet 属性标签,它与故事板中的标签相连接:





我要修改文字标签使用此代码,但没有任何更改:

  testController.label。 text = @newText; 
[self.view addSubview:testController.view];

testController 是一个有效的实例, label 为零。
我错过了什么?

解决方案

您的 UILabel nil ,因为您已经实例化了您的控制器,但它没有加载其视图。控制器的视图层次结构在您第一次请求访问其视图时加载。所以,正如@lnafziger建议(虽然应该重要的这个确切的原因)如果你切换两行它将工作。所以:

  [self.view addSubview:testController.view]; 
testController.label.text = @newText;作为一个例子来说明这一点,即使这个也可以工作:


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

这篇关于如何访问从storyboard加载的视图控制器的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆