我在计算UIProgressView的进度时遇到问题。我的浮动值对进度没有影响。我试图手动设置进度它工作正常,但如果我尝试计算它它不起作用。
这是我的代码:
- (void) initProgressbar {
self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
[self.progressView setFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2, 10)];
self.progressView.center = CGPointMake(SCREEN_WIDTH - 110, SCREEN_HEIGHT - 25);
self.progressView.progress = 0.0;
[self.view addSubview:self.progressView];
}
nbElementsSync
和nbElementsToSync
是全局int属性,nbElementsSync
在调用updateProgress
方法之前循环递增。
MyController.h
@interface MyController : UIViewController {
NSString *json;
int nbElementsToSync;
int nbElementsSync;
}
@property (nonatomic, strong) UIProgressView *progressView;
MyController.m
nbElementsSync = 0; // Nb elements synchronized
nbElementsToSync = [[json valueForKey:@"count"] intValue]; // Nb elements to synchronize
for (NSString* result in results) {
nbElementsSync++;
[self updateProgress];
}
这是我设置进度的方法:
- (void) updateProgress {
[self.progressView setProgress:((float)nbElementsSync / nbElementsToSync)];
NSLog(@"percent : %f", ((float)nbElementsSync / nbElementsToSync));
}
我的NSLog的结果:
percent : 0.003937
percent : 0.007874
percent : 0.011811
percent : 0.015748
percent : 0.019685
percent : 0.023622
...
有什么想法解决它吗?提前谢谢。
答案 0 :(得分:3)
您是否尝试在后台进程中执行循环,而不是阻止UI更新:
<强> MyController.m 强>
在需要的地方拨打电话:
[self performSelectorInBackground:@selector(syncInBackground) withObject:nil];
然后
- (void)syncInBackground
{
int nbElementsSync = 0; // Nb elements synchronized
int nbElementsToSync = [[json valueForKey:@"count"] intValue]; // Nb elements to synchronize
for (NSString* result in results) {
nbElementsSync++;
float percent = (float)nbElementsSync / nbElementsToSync;
[self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:percent] waitUntilDone:NO];
}
}
- (void) updateProgress:(NSNumber *)percent {
[self.progressView setProgress:percent.floatValue];
}