Objective-C Question

Progress in label

Use code for show downloading progress in percent

float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];

NSString *percentage = [NSString stringWithFormat:@"%d%%", (int)((progress/total)*100)];
[_label setText:[NSString stringWithFormat:@"%@%%", percentage]];
_label = [[UILabel alloc]initWithFrame:CGRectMake(323.43, 148.84, 42, 19)];
[_label setText: percentage];
_label.numberOfLines = 1;
_label.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
_label.adjustsFontSizeToFitWidth = YES;
_label.minimumScaleFactor = 10.0f/12.0f;
_label.clipsToBounds = YES;
_label.backgroundColor = [UIColor blackColor];
_label.textColor = [UIColor whiteColor];
_label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_label];


If I use
_label.backgroundColor = [UIColor blackColor];
progress label work correctly. But if I use
_label.backgroundColor = [UIColor clearColor];
numbers superimposed on each other

Why?

_label.backgroundColor = [UIColor blackColor];

enter image description here

_label.backgroundColor = [UIColor clearColor];
enter image description here

Answer

You are adding multiples labels with the method [self.view addSubview: _label] If you want to see that more visually use the Debug View Hierarchy when you are debugging. To solve the issue you can check if the _label is not nil and you will set only the text. See the code below:

    float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
    float total = [[NSNumber numberWithInteger:totalBytesExpectedToWrite] floatValue];

    NSString *percentage = [NSString stringWithFormat:@"%.f%%", ((progress / total) * 100)];

    if (!_label) {

        _label = [[UILabel alloc] initWithFrame:CGRectMake(323.43, 148.84, 42, 19)];

        _label.numberOfLines = 1;
        _label.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
        _label.adjustsFontSizeToFitWidth = YES;
        _label.minimumScaleFactor = 10.0f/12.0f;
        _labellabel.clipsToBounds = YES;
        _label.backgroundColor = [UIColor blackColor];
        _label.textColor = [UIColor whiteColor];
        _label.textAlignment = NSTextAlignmentCenter;

        [self.view addSubview:_label];
   }

   _label.text = percentage;

Notice that you are trying to set the text before initialize it: [_label setText:[NSString stringWithFormat:@"%@%%", percentage]]; and if _label is nil the app crash in that point. Try to avoid set the frame manually instead of that use auto layout.