![](/img/trans.png)
[英]Can't set text color of UILabel implemented as custom view to UIBarButtonItem
[英]can't set UILabel text from my custom NSObject class
这是我的viewController类,其中的标签通过IBOutlet连接,而我的ViewController.h是
而我的ViewController.m是
我想在其中设置ViewController标签文本的自定义类和自定义类如下:customVC.h如下所示
与其在您的init
方法中设置“ .label
”, .label
在您的“ viewDidLoad:
”方法或“ viewWillAppear:
”方法中进行设置。
这样做的原因是因为在视图控制器的“ init
”时,还没有从XIB或Storyboard文件中加载标签和所有其他用户界面元素。
ps目标C中的最佳做法是以小写字母开头所有变量和属性。 因此,而不是“ .Label
”使用“ .label
”,甚至更好,更具描述性的,如“ .viewControllerTitleLabel
”。
我可以看到您的CustomVC.h文件吗?
我假设您的意图是要CustomVC扩展ViewController类。
所以需要
@interface CustomVC : ViewController
在您的CustomVC.h中
然后在您的CustomVC.m中
-(id)init{
if(self = [super init]){
[self.Label setText:@"hello world"];
}
return self;
}
您不再需要分配viewController对象。
无需分配-在您的customVC类中再次初始化视图控制器,每次您分配init时,都会为对象提供一个单独的引用,在这种情况下,这似乎就像您使用以下命令为视图控制器设置标签文本一样不同的参考,而不是您要尝试的参考
我建议您将当前视图控制器的引用传递给这样的init方法
- (id)initForVC:(ViewController *)refVC
{
self = [super init];
if (self) {
[refVC.Label setText:@"Hello World"];
}
return self;
}
只需在customVC的.m文件中添加此函数及其定义
- (id)initForVC:(ViewController *)refVC;
在.h文件中
您的viewcontroller的viewDidLoad
将更改为此
- (void)viewDidLoad
{
[super viewDidLoad];
customVC *customVC = [[customVC alloc] initForVC:self];
}
而不是直接将文本设置为NSString类的UILabel对象的create属性,然后将文本设置为该属性,然后将NSString属性分配给UILabel,它将起作用。
NSString *str = [NSString stringWithFormat: @"Sample..."];
FirstViewController *f = [[FirstViewController alloc]initWithNibName:@"FirstViewController" bundle:nil];
f.lbl = str; //lbl is the NSString property
[self.navigationController presentViewController:f animated:YES completion:nil];
然后将lbl分配给UILabel对象
lblText.text = lbl;
伙计们,我通过使用NSNotificationcenter解决了这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.