Tori
Tori

Reputation: 1356

Accessing a label defined locally

My app has a method that creates a label

     -(void)addLabel:(float)x:(float)y:(float)w:(float)h:(NSString *)text {
        CGRect label1Frame = CGRectMake( x, y, w, h );
        UILabel *label1 = [[UILabel alloc] initWithFrame: label1Frame];
        label1.text = text;
        [self.view addSubview:label1];}

Then I call this method from other methods.

How can I access one of these labels to remove it from the superview, as I don't have an var name for it.

Upvotes: 0

Views: 46

Answers (2)

user529758
user529758

Reputation:

-(void)addLabel:(float)x :(float)y :(float)w :(float)h :(NSString *)text tag:(NSInteger)tag {
    CGRect label1Frame = CGRectMake( x, y, w, h );
    UILabel *label1 = [[UILabel alloc] initWithFrame: label1Frame];
    label1.tag = tag;
    label1.text = text;
    [self.view addSubview:label1];
}

Then pass in an appropriate tag value (an integer) which is unique. Then use:

UILabel *label = (UILabel *)[self.view viewWithTag:someIntID];

to access it.

Upvotes: 1

J2theC
J2theC

Reputation: 4452

You need to create an ivar/property to it. If you dont want to have this label on your interface, declare a class extension inside your implementation file and declare your label

@interface yourclass()
@property (nonatomic, weak)UILabel *yourLabel;
@end

Remember to add your @synthesize to your implementation file. Assign the value to the property after adding the label as a subview.

Upvotes: 0

Related Questions