简体   繁体   中英

can't set UILabel text from my custom NSObject class

this is my viewController class where my label is connectd through IBOutlet and my ViewController.h is 在此处输入图片说明

and my ViewController.m is 在此处输入图片说明

and my custom class from where I want to set ViewController label text and my custom class look like this my customVC.h look like this

在此处输入图片说明

在此处输入图片说明

Instead of setting the " .label " in your " init " method, do it in your " viewDidLoad: " method or your " viewWillAppear: " method.

The reason for this is because at the view controller's " init " time, the label and all other user interface elements haven't been loaded from the XIB or Storyboard file yet.

ps best practice in Objective C is to start ALL variables and properties with lower case letters. So instead of " .Label " use " .label ", or even better, something more descriptive, like " .viewControllerTitleLabel ".

Can I see your CustomVC.h file?

I assume that your intention is to CustomVC extend the ViewController Class.

so there's need to be

@interface CustomVC : ViewController

in your CustomVC.h

then in your CustomVC.m it should be

-(id)init{
   if(self = [super init]){
       [self.Label setText:@"hello world"];
  }
  return self;
}

you don't need to allocate the viewController object anymore.

There is no need to alloc - init the view controller again in your customVC class, every time you alloc init something a separate reference is provided to the object, which in this case seems to be like you are setting label text for a view controller with different reference rather than the one in which you are trying to

I suggest you to pass reference of your current view controller to your init methods like this

- (id)initForVC:(ViewController *)refVC
{
    self = [super init];
    if (self) {
        [refVC.Label setText:@"Hello World"];
    }
    return self;
}

Just add this function in .m file of customVC and it's definition

- (id)initForVC:(ViewController *)refVC;

in .h file

Your viewcontroller's viewDidLoad will change to this

- (void)viewDidLoad
{
    [super viewDidLoad];
    customVC *customVC = [[customVC alloc] initForVC:self];
}

instead of directly setting text to UILabel object create property of NSString class and set the text to that property and then then assign NSString property to UILabel, It will work.

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

and then assign lbl to UILabel object

lblText.text = lbl;

伙计们,我通过使用NSNotificationcenter解决了这个问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM