使用代码以百分比显示下载进度
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];
如果我使用_label.backgroundColor = [UIColor blackColor];
进度标签正常工作。但是,如果我使用_label.backgroundColor = [UIColor clearColor];
个数字叠加在一起
为什么?
答案 0 :(得分:0)
您似乎正在添加多个标签[self.view addSubview: _label]
。此代码只应执行一次。在黑色背景下,您只能看到最顶部的标签。背景清晰,你可以看到所有
答案 1 :(得分:0)
您正在使用方法[self.view addSubview: _label]
添加多个标签如果您希望在调试时更直观地使用Debug View Hierarchy。
要解决此问题,您可以检查_label是否为nil,并且只设置文本。请参阅以下代码:
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;
请注意,您正在尝试在初始化文本之前设置文本:[_label setText:[NSString stringWithFormat:@"%@%%", percentage]];
如果_label为nil,则应用程序崩溃。
尽量避免手动设置框架而不是使用自动布局。
答案 2 :(得分:0)
我认为,标签已经重叠了。所以你可以使用" tag"每次都删除标签并重新创建它的值。
添加标记
_label = [[UILabel alloc] initWithFrame:CGRectMake(323.43, 148.84, 42, 19)]; // after you will set the tag for the required Label.
_label.tag = 505;
删除并重新创建标签
[[self.view viewWithTag:505]removeFromSuperView]; // after you will create the Label
_label = [[UILabel alloc] initWithFrame:CGRectMake(323.43, 148.84, 42, 19)];