Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Updating ViewController UILabel from another Class

I'm new to development and been banging my head against a wall trying to figure this out, I'm sure, that I'm missing something silly but after trying various different solutions, I'm still unable to get the result I'm looking for.

I would like to be able to update a UILabel in a ViewController from another class, here is a little demo program that I cannot get to work, I have the ViewController which has two UILabels, one is updated from with the viewDidDoad and the other one I would like to update from the other class called NewClass which is called from ViewController, I can the see the class is being called correctly as the console is logging the NSLog entry but I cannot get the syntax for updating the UILabel.

Thanks in advance.

ViewController.h

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController {

   UILabel *_labelupdate01;
   UILabel *_labelupdate02;     
 }

 @property (nonatomic, retain) IBOutlet UILabel *labelupdate01;
 @property (nonatomic, retain) IBOutlet UILabel *labelupdate02;

 @end

ViewController.m

#import "ViewController.h"
#import "NewClass.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize labelupdate01;
@synthesize labelupdate02;


- (void)viewDidLoad
{
    [super viewDidLoad];

    labelupdate01.text = @"Update from ViewController";

    [NewClass updatedisplay];
}
@end

NewClass.h

#import <Foundation/Foundation.h>

@class ViewController;

@interface NewClass : NSObject

@property (nonatomic, assign) ViewController *ViewController;

+ (void)updatedisplay;

@end

NewClass.m

 #import "NewClass.h"
 #import "ViewController.h"

 @implementation NewClass

 @synthesize ViewController = _ViewController;

 + (void)updatedisplay
 {
     NSLog(@"NewClass - updatedisplay");
     ViewController *labelupdate02;
     labelupdate02.labelupdate02.text = @"Update from NewClass";
 }

 @end
like image 238
Wez Avatar asked Mar 24 '13 22:03

Wez


2 Answers

define this in newClass like that

+ (void)updatedisplay:(ViewController *)vc
{
     vc.labelupdate02.text=@"Update from NewClass";

}

and call it from your viewController

[NewClass updatedisplay:self];
like image 150
meth Avatar answered Sep 21 '22 23:09

meth


First, make sure you initialize ViewController in NewClass, then you can do whatever you want with it.

#import <Foundation/Foundation.h>

@class ViewController;

@interface NewClass : NSObject

@property (nonatomic, assign) ViewController *aViewController;

+ (void)updatedisplay;

@end

In implementation

 #import "NewClass.h"
 #import "ViewController.h"

 @implementation NewClass

 + (void)updatedisplay
 {

 _aViewController.labelupdate02.text = @"Update from NewClass";

 }

 @end
like image 31
David Avatar answered Sep 21 '22 23:09

David