George Johnston
George Johnston

Reputation: 32258

Xcode Adding a label, and setting the text

I am extremely new to objective c development. I used a tutorial to learn how to add a label at run time, but I'm a little confused how to reference it later.

If I add...

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
myLabel.text = @"My Label";
[self.view addSubview:myLabel];

...in my viewDidLoad method, how can I reference that label from another method on a separate occasion? Unlike C#, I don't name the label for later reference -- so I can't simply reference the name to set it.

Upvotes: 1

Views: 26194

Answers (2)

Black Frog
Black Frog

Reputation: 11713

  1. You can hold on to a reference to the UILabel with an ivar.
  2. You can search the UIView for the tag with: -viewWithTag method. Providing you set the tag property before release it. :-)

Upvotes: 1

Ole Begemann
Ole Begemann

Reputation: 135548

You have to declare an instance variable for the label in your class's @interface (and optionally also a property for the ivar). Then assign the label to the ivar/property in viewDidLoad and you can use it later in every other method of the class.

Don't forget to release the label in your -dealloc method. The code in your question leaks memory.

Upvotes: 2

Related Questions