Faisal Syed
Faisal Syed

Reputation: 931

UILabel not hidden when set to Hidden

My app receives a measurement every minute. When the measurement is 0, I want a label to be displayed in the middle. When it is greater than that, when I want the label to disappear. The issue I have is that once the label appears, it doesn't hide once I set its hidden mode to true.

 UILabel *emptyBagLabel = [[UILabel alloc] init];
    emptyBagLabel.textAlignment = NSTextAlignmentCenter;
    emptyBagLabel.textColor = [UIColor darkGrayColor];
    emptyBagLabel.numberOfLines = 0;
    emptyBagLabel.text = @"EMPTY POUCH";
    emptyBagLabel.translatesAutoresizingMaskIntoConstraints = NO;
    emptyBagLabel.hidden = true;

    [self addSubview:emptyBagLabel];

    [emptyBagLabel.centerXAnchor constraintEqualToAnchor:self.centerXAnchor].active = YES;
    [emptyBagLabel.centerYAnchor constraintEqualToAnchor:self.centerYAnchor].active = YES;
    [emptyBagLabel.widthAnchor constraintEqualToAnchor:self.widthAnchor].active = YES;
    [emptyBagLabel.heightAnchor constraintEqualToConstant:100].active= YES;

    if (measurement == 0 || measurement <= 0.005) {
        emptyBagLabel.hidden = false;
    }

    if (measurement > 0.005) {
        emptyBagLabel.hidden = true;
    }

I've been scratching my head at this for a while, a bit frustrated with how I'm not able to solve such a trivial issue. The method I have it in is called every minute. I know the method and the hidden = true line are getting called, so I'm unsure as to what is causing the issue.

Upvotes: 3

Views: 554

Answers (1)

danh
danh

Reputation: 62676

Subviews that are added programmatically ought to be added lazily, so you get exactly one subview instance. I'd refactor the code like this...

- (UILabel *)emptyBagLabel {
    UILabel *emptyBagLabel = (UILabel *)[self.view viewWithTag:128];
    if (!emptyBagLabel) {
        emptyBagLabel = [[UILabel alloc] init];
        emptyBagLabel.tag = 128;

        // set all of the attributes her for how the label looks, textColor, etc.
        // everything except the properties that change over time

        [self addSubview:emptyBagLabel];
    }
    return emptyBagLabel;
}

// if this view is built using initWithFrame...
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self emptyBagLabel];  // to add the label initially
    }
    return self;
}

// if this view is ever loaded from a nib, then
- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self emptyBagLabel];
    }
    return self;
    
}

// elsewhere in the view, when you get the measurement
// side note: alpha is usually a better choice than hidden because you can animate it
if (measurement == 0 || measurement <= 0.005) {
    self.emptyBagLabel.alpha = 1.0;
}

if (measurement > 0.005) {
    self.emptyBagLabel.alpha = 0.0;
}

Upvotes: 4

Related Questions