我的应用每分钟都会收到一次测量。当测量值为0时,我希望在中间显示标签。当它大于那个时,我希望标签消失。我遇到的问题是,一旦标签出现,一旦我将其隐藏模式设置为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;
}
我一直在摸不着头脑,对我如何解决这样一个微不足道的问题感到有点沮丧。我每分钟都会调用它的方法。我知道方法和hidden = true行被调用,所以我不确定是什么导致了这个问题。
答案 0 :(得分:3)
以编程方式添加的子视图应该是懒惰添加的,因此您只能获得一个子视图实例。我像这样重构代码......
- (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;
}