![](/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.