2017-01-30 6 views
3

私のアプリは毎分測定を受け取ります。測定値が0の場合は、ラベルを中央に表示します。それよりも大きいときは、ラベルを消したいとき。私が持っている問題は、いったんラベルが表示されたら、隠しモードをtrueに設定するとラベルが表示されなくなります。隠しファイルに設定するとUILabelが非表示になる

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; 
    } 

私は、このような些細な問題を解決することはできないんだけどどのようにして少しイライラし、しばらくの間、この時に私の頭を悩まてきました。私が持っている方法は、毎分と呼ばれています。私はその方法を知っていて、隠された真の行が呼び出されているので、問題の原因を確かめている。

+2

しかし、あなたは以前、私が見る1 – redent84

+0

は、その後、どのように私はこれを処理して行くべきで隠れていない、新しいラベルにそのメソッドが呼び出されるたびに作成していますか? –

+0

あなたの最初のラベルへの参照を保持し、そのラベルに '.hidden = true'を呼び出します。 – redent84

答えて

3

プログラムで追加されたサブビューは遅れて追加する必要があるため、正確に1つのサブビューインスタンスを取得します。私はこのようなコードをリファクタリングしたい...

- (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; 
} 
+0

私はself.emptyBagLabelへのアクセス権を持っていません。 –

+0

@FaisalSyedそのメソッドを追加すると、 'self.emptyBagLabel'かそれ以上の' [self emptyBagLabel] 'は正常に動作します。 – danh

+0

ああ、私は参照してください。私はviewDidLayoutSubviewsへのアクセス権を持っていないので、このコードはUIViewの - (void)drawRectです。私はちょうどinitメソッドでラベルを追加する必要がありますか? –

関連する問題