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
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];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With