Обновите UIProgressView в UICollectionViewCell для загрузки файла

Я пытаюсь обновить UIProgressView в UICollectionViewCell, когда загружаю файл, но иногда обновление 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;
}

Это кнопка для начала загрузки:

- (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]];
}

Один раз представление прогресса работает, а другое тысячу раз не работает, я не могу понять, как обновить представление прогресса, любая помощь?


person Piero    schedule 07.01.2013    source источник


Ответы (2)


Создайте свой customCell и отобразите в нем все видимые UIViews (init, add subview...). Затем используйте пользовательский метод в cellForItemAtIndexPath, чтобы активировать (отобразить) его. Если вы думаете о MVC, cellForItemAtIndexPath только для контроллера, а не для представления.

В вашем случае перенесите все IBAction, loadLink и updateProgress в customCell и отправьте параметр, чтобы активировать их, или вы можете создать новый протокол, такой как CustomCellDelegate, для связи.

Проверьте для получения дополнительной информации:

Ошибка установки текста в ячейке представления коллекции

person LE SANG    schedule 13.01.2013
comment
большое спасибо за ответ, сначала я приму ваш ответ, можете ли вы создать пример кода, в котором объясните решение, простое представление uicollection и подкласс uicollectioviewcell, а также вставьте uiimageview, который загружает изображение из URL-адреса и отображает его в uicollectionviewcell, чтобы я мог видеть, как использовать этот класс, я буду очень признателен, если вы сделаете этот пример кода :( спасибо - person Piero; 13.01.2013
comment
большое спасибо! поэтому я должен добавить код загрузки в uicollectionviewcell? - person Piero; 14.01.2013
comment
и если я хочу, чтобы класс, который обрабатывает всю загрузку, обрабатывал очередь, как я могу отправить обновление индикатора выполнения в подкласс uicollectionviewcell? - person Piero; 14.01.2013
comment
привет, @Sang взгляните на этот вопрос, stackoverflow.com/questions/14542188/ я написал код для вашего запроса, и он не работает :( помогите! - person Piero; 27.01.2013

Это может быть связано с проблемой резьбы. просто попробуй

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

попробуй асинхронно или синхронно

person Güngör Basa    schedule 07.01.2013