更新UICollectionViewCell中的UIProgressView以获取下载文件

我试图更新UICollectionViewCell中的UIProgressView当我下载一个文件,但有时progressView更新和有时不更新,我不明白为什么,这是显示UICollectionViewCell的代码:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"documentCell"; UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; NSManagedObject *doc = [self.magDocument objectAtIndex:indexPath.row]; UIButton *btn = (UIButton *)[cell viewWithTag:2003]; [btn addTarget:self action:@selector(addDocument:) forControlEvents:UIControlEventTouchUpInside]; UIProgressView *progressBar = (UIProgressView *)[cell viewWithTag:2005]; return cell; } 

这是开始下载的button:

 - (IBAction)addDocument:(id)sender { self.directCellPath = [self.myCollectionView indexPathForCell:(UICollectionViewCell *)[[sender superview] superview]]; NSManagedObject *document = [self.magDocument objectAtIndex:self.directCellPath.row]; [self loadLink:[document valueForKey:@"docUrl"]]; } - (void)loadLink:(NSString *)urlDownload { UICollectionViewCell *cell = (UICollectionViewCell *)[self.myCollectionView cellForItemAtIndexPath:self.directCellPath]; UIProgressView *prg = (UIProgressView *)[cell viewWithTag:2005]; AFDownloadRequestOperation *request = [[AFDownloadRequestOperation alloc] initWithRequest:requestUrl targetPath:zipDownloadPath shouldResume:YES]; [request setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) { NSLog(@"%f",totalBytesReadForFile/(float)totalBytesExpectedToReadForFile); NSArray *progress = [NSArray arrayWithObjects:prg,[NSNumber numberWithFloat:totalBytesReadForFile/(float)totalBytesExpectedToReadForFile], nil]; [self performSelectorOnMainThread:@selector(updateProgressBar:) withObject:progress waitUntilDone:NO]; }]; [self.downloadQueue addOperation:request]; } - (void)updateProgressBar:(NSArray *)progress { UIProgressView *pgr = (UIProgressView *)[progress objectAtIndex:0]; [pgr setProgress:[[progress objectAtIndex:1] floatValue]]; } 

有一次进度视图工作,其他一千次不起作用,我无法理解如何更新进度视图,有什么帮助?

创build你的customCell并在其中显示所有可见的UIViews(初始化,添加子视图…)。 在cellForItemAtIndexPath中使用自定义方法来激活(显示)它。 如果你考虑MVC,cellForItemAtIndexPath只是Controller,而不是View。

你的情况,把所有的IBAction,loadLink和updateProgress到customCell并发送参数来激活它们,或者你可以创build新的协议,如CustomCellDelegate进行通信。

检查更多信息:

收集视图单元格中的文本设置出错

这可能是关于线程问题。 你试一试

 dispatch_async(dispatch_get_main_queue(), ^{ UIProgressView *pgr = (UIProgressView *)[progress objectAtIndex:0]; [pgr setProgress:[[progress objectAtIndex:1] floatValue]]; });//end block 

尝试asynchronous或同步