Search code examples
ioslabelcgrectmake

Can't remove a label programmatically


I am printing a label programmatically but I can't remove it from the screen. I have tried removeFromSuperview and lbl1.hidden = YES; and lbl1= nil; but non of them work. It stays on the screen all the time while I can see in the debug it pass from ELSE as in the code below.

Where would be my problem?

-(void)reloadData
lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(320, 530, 550, 200)];

if (result1 > result2 &&  al == YES)
{
    lbl1.userInteractionEnabled = YES;
    lbl1.text = @" Warning!! ";
    lbl1.tag = 30;
    lbl1.font = [UIFont fontWithName:@"Helvetica" size:18.0];
    lbl1.textColor = [UIColor redColor];
    lbl1.backgroundColor = [UIColor clearColor];
    lbl1.lineBreakMode = NSLineBreakByWordWrapping;
    lbl1.numberOfLines = 2;
    [self addSubview:lbl1];
    [lbl1 release];
}

else{

    //Non of them is removing the label.
    [lbl1 removeFromSuperview];
    lbl1= nil;
    lbl1.hidden = YES;
}

Solution

  • Every time you go into reloadData, you are creating a new label, so if you go into reload and jump to the else, you are creating a label, and then removing it.

    You need to save that label as an instance variable and remove it/add it in your reloadData.

    @property(nonatomic, strong) UILabel *lbl1;
    

    And in your code, do this only ONCE:

    self.lbl1 = [[[UILabel alloc] initWithFrame:CGRectMake(320, 530, 550, 200)] autorelease];
    

    And in your reloadData do:

    -(void)reloadData
    lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(320, 530, 550, 200)];
    
    if (result1 > result2 &&  al == YES)
    {
        self.lbl1.userInteractionEnabled = YES;
        //Etc...
    }
    
    else{
    
        [self.lbl1 removeFromSuperview];
    }