【问题标题】:Frame size doesn't update directly after being called from NSURLConnection delegate?从 NSURLConnection 委托调用后,帧大小不会直接更新?
【发布时间】:2012-01-18 13:34:31
【问题描述】:

我正在下载一些图片并创建了一个进度条。我正在使用 NSURLConnection 的异步模式并同时启动大约 15 张图片下载。在启动过程中,我调用didStartLoadImages 并且栏已成功设置为屏幕上的 0 宽度。

现在问题开始了,当其中一张图片完成后,它将调用didLoadImageWithTotalPercentCompleted: 并使用当前百分比更新栏。它工作得很好,日志写得很好 将帧更新为:20% 等。但是用户界面不会更新直到所有图像都完成?

我只是注意到主线程被阻塞了,即使它是异步的?

连接.m

-(void)loadImage:(NSString*)imageName numberOfImagesInSecquence:(int)nrOfImages {
    NSString *url = [NSString stringWithFormat:@"https://xxx.xxx.xxx.xxx/~%@/files/%@",site,imageName];

    /* Send URL */
    NSURL *urlToSend = [[NSURL alloc] initWithString:url];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlToSend];
    theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];

    self.receivedData = [NSMutableData data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    connectionIsLoading = NO;
    [[self delegate] didLoadImagesWithProcent:((float)1 - ((float)[imageArray count] / (float)nrOfImages)) *(float)100];
}

MainViewController.m

-(void)didStartLoadImages {
     /* Sets progress bar to 0% */
     [progressBar setBarWithPercent:0];
}


-(void)didLoadImageWithTotalPercentCompleted:(int)percent {
    if (percent == 100) {
        /* Done */
    } else {
        [progressBar setBarWithPercent:percent];
    }
}

进度条.m

-(void)setBarWithPercent:(float)percent {
    int maxSizeOfBar = 411;

    [UIView beginAnimations:@"in" context:NULL];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationBeginsFromCurrentState:YES];

    CGRect frame = bar.frame;
    frame.size.width = maxSizeOfBar * (percent / 100) + 10;
    bar.frame = frame;
    NSLog(@"Updating frame to: %i",percent);

    [UIView commitAnimations];

}

【问题讨论】:

    标签: objective-c ios ios5 nsurlconnection


    【解决方案1】:

    这可能是整数数学截断的问题。将您的百分比值更改为浮点数或 CGFloat 而不是 int,并将所有数字写成 100.0f 而不是 100 以强制 C 将它们视为浮点数而不是整数。

    基本上,在 C 语言中,如果你做 1/2,它不会给你 0.5,它会给你 0,因为它使用整数数学,并且 2 不会变成 1 的整数次。因此,在计算百分比时,您确实希望使用浮点数,因为 (1/100) * x 将始终为零,但 (1.0f/100.0f) * x 将正常工作。

    【讨论】:

    • 你拯救了我的一天!当我在didLoadImageWithTotalPercentCompleted:(int)percent 中从 int 更改为 float 时,现在可以完美运行。我永远不会看到那个错误。谢谢!
    猜你喜欢
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 2013-10-15
    • 2014-07-03
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多