HurkNburkS
HurkNburkS

Reputation: 5510

access UILabel using tag notation

I have created several UILabels each with their own .tag value. I am then trying to populate the UILabel with a NSString from another class which calls a method from the calls that has set the UILabels using the .tag

however when I try to access the label in my debug section its showing the label as null and the text is never set.

this is what my method looks like thats being called from the other calss.

- (void) SymbolButtonPressed:(NSString *)selectedString {

    UILabel *label = (UILabel *)[cutField viewWithTag:currentlySelectedTag];
    [label setText:selectedString];

}

label = null when I am debugging this code... I am not sure why

as requested this is how I add the label

axesView = [[UIView alloc] init];
axesView.frame = CGRectMake(0.0, 0.0, scrollWidth+10, 77.0);


cutField = [[UILabel alloc] initWithFrame:CGRectMake((i*40)+2, 35, 40, 40)];
cutField.textColor = [UIColor blackColor];
[cutField setTextAlignment:NSTextAlignmentCenter];
cutField.font = [UIFont fontWithName:@"Helvetica" size:20];
cutField.backgroundColor=[UIColor whiteColor];
cutField.layer.borderColor = [[UIColor colorWithRed:colorController.grRed/255.0 green:colorController.grGreen/255.0 blue:colorController.grBlue/255.0 alpha:1.0] CGColor];
cutField.layer.borderWidth = 0.5f;
[axView addSubview:cutField];

Upvotes: 0

Views: 1551

Answers (1)

Duncan C
Duncan C

Reputation: 131408

As the others have hinted at, you almost always want to use your view controller's content view in calls to viewWithTag. That method will walk all the subviews, sub-views, and sub-subviews until it finds your tag. By using self.view, it works no matter where the tagged view is in your view hierarchy, and works even if you move the view into a different subview later (which happens more often than you think.)

Upvotes: 1

Related Questions