Mattigins
Mattigins

Reputation: 1016

How do I access a dynamically loaded label from a method that didn't create it using Cocoa-Touch?

I need to set the text of a label from a method that didn't create it.

The label is created on viewdidload and the method that needs to change the label is not in viewdidload.

Help is much appreciated.

Upvotes: 0

Views: 72

Answers (2)

Saleh
Saleh

Reputation: 380

make the uilabel as the instance variable of the class. initialize it in viewdidload and set the text in whichever method you want.

EDIT: Check this code example: In header:

UILabel *myLabel;

In implementation:

-(void) viewDidLoad {
     myLabel = [[UILabel alloc] initWithFrame:myFrame]];
     [self.view addSubview:mylabel]
 }
 -(void)sumOtherMethod {
     myLabel.text = @"this is my text";
 } 

Upvotes: 0

Manish Ahuja
Manish Ahuja

Reputation: 4517

You can create that UILabel as property as:

in YourClass.h

@property (nonatomic, retain) UILabel *myLabel;

Synthesize it in YourClass.m

@synthesize myLabel;

now when you create this label in viewDidLoad method do it like this

self.myLabel = [[UILabel alloc] init] autorelease];
//set the frame, color and text properties here
self.myLabel.text = @"initial text";
self.myLabel.frame =  CGRectMake(0,0,30,100);

And whenever you need to access the UILabel to update any of it's properties like text you can do it by using the self accessor as:

self.myLabel.text = @"Updated text here";

When you do this make sure you set myLabel to nil in viewDidUnload to handle memory properly.

Upvotes: 2

Related Questions