0

Я уже задал тот же вопрос о сохранении нажатого состояния кнопки, и я подумал, что должен делать то же самое, чтобы сохранить состояние состояния на ячейках, но мои попытки не увенчались успехом.Сохранить состояние выполнения UICollectionViewCell

Что я сейчас делаю: я выбираю UICollectionViewCell's, а затем нажмите кнопку «скачать», а затем начнется действие downolad. Каждая ячейка, которую я выбрал, показывает UIProgressView, и все в порядке, пока я не прокручу UICollectionView вверх или вниз. Когда я делаю это, у других ячеек тоже есть прогресс, но они не должны! Я знаю, что я должен сохранить indexPath выбранных ячеек в NSMutableArray, а затем в cellForItemAtIndexPath проверить, находится ли текущая ячейка indexPath в моем массиве, а затем показать или скрыть объекты моей ячейки. Я делаю это, но он работает только с выбором ячеек! Что я должен сделать, чтобы сохранить состояние прогресса в каждой ячейке, этот прогресс действительно существует?

Вот мой код:

В cellForItemAtIndexPath:

NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)indexPath.row]; 
if ([selecedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]] ) 
{ 

    cell.selectedBG.hidden = NO; 
    cell.selectedImg.hidden = NO; 


} 
else 
{ 

    cell.selectedBG.hidden = YES; 
    cell.selectedImg.hidden = YES; 
    cell.progressView.hidden = YES; 


} 

В didSelectItemAtIndexPath:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
... 
     // Add the selected item into the array 
     [selectedIds addObject:selectedId]; 
     [selectedVideos addObject:selectedVideo]; 
     AVMVideoCell *collectionCell = (AVMVideoCell*)[collectionView cellForItemAtIndexPath:indexPath]; 
     NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)indexPath.row]; 
     if (![selecedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]] ) 
     { 
      [selecedCellsArray addObject:[NSString stringWithFormat:@"%ld",(long)indexPath.row]]; 
      collectionCell.selectedBG.hidden = NO; 
      collectionCell.selectedImg.hidden = NO; 
      [collectionCell setSelected:YES]; 
     } 
    } 
} 

В didDeselectItemAtIndexPath:

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath { 
    ... 

    // Delete the selected item from the array 
    [selectedIds removeObject:selectedId]; 
    [selectedVideos removeObject:selectedVideo]; 
    AVMVideoCell *collectionCell = (AVMVideoCell*)[collectionView cellForItemAtIndexPath:indexPath]; 
    NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)indexPath.row]; 
    if ([selecedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]] ) 
    { 
     [selecedCellsArray removeObject:[NSString stringWithFormat:@"%ld",(long)indexPath.row]]; 
     collectionCell.selectedBG.hidden = YES; 
     collectionCell.selectedImg.hidden = YES; 
     [collectionCell setSelected:NO]; 

    } 
} 

И это, как я показать свой прогресс:

-(NSString *)progress:(long long)val1 : (long long)val2 : (AVMVideoCell *)cell : (NSString *)name : (NSIndexPath *)path{ 

float progress = ((float)val1)/val2; 
NSString *prog = [[NSNumber numberWithFloat:progress*100] stringValue]; 
if (prog != nil){ 
    if(cell.isSelected){ 
    cell.selectedImg.hidden = YES; 
    cell.progressView.hidden = NO; 
    } 
} 


NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)path.row]; 
if ([selecedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]]) 
{ 
[cell.progressView setProgress:progress animated:YES]; 
} 

if([prog intValue]==100){ 
    cell.progressView.hidden = YES; 

} 
return prog; 
} 

EDIT: AVMVideoCell.m

#import "AVMVideoCell.h" 


@implementation AVMVideoCell 
{ 
    NSString *fullUrl; 
} 
@synthesize imageView; 
@synthesize selectedBG; 
@synthesize progressLabel; 
@synthesize progressView; 
@synthesize selectedImg; 
@synthesize progLayer; 

-(void) setVideo:(AVMDataStore *)video { 
if(_video != video) { 
    _video = video; 
} 
NSString *durString = [NSString stringWithFormat:@"%@",[self timeFormatted:_video.duration]]; 
if((_video.filePreview != nil) && ![_video.filePreview isEqualToString:@""]){ 
fullUrl = [NSString stringWithFormat:@"http://example.com%@",_video.filePreview]; 
} 

NSURL *imgURL = [NSURL URLWithString:fullUrl]; 

[self.imageView setImageWithURL:imgURL 
       placeholderImage:[UIImage imageNamed:@"yesterday.png"] options:0 usingActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; 
self.duration.text = durString; 

} 

- (NSString *)timeFormatted:(int)totalSeconds 
{ 

int seconds = totalSeconds % 60; 
int minutes = (totalSeconds/60) % 60; 
int hours = totalSeconds/3600; 

return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds]; 
} 
@end 

EDIT 2: Разъяснение о прогрессе Мой progressView не a IBOutlet это @property (nonatomic,strong) UIProgressView *progressView; (AVMVideoCell.h)

выделяет и инициализировать его в cellForItemAtIndexPath:

cell.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,0, 150.0f, 1.0f)]; 
cell.progressView.trackTintColor = [UIColor colorWithWhite:255 alpha:0.5f]; 
cell.progressView.progressTintColor = [UIColor whiteColor]; 
[cell.progLayer addSubview:cell.progressView]; 
cell.progressView.hidden = YES; 
cell.progressView.tag = indexPath.row+500; 

Это где я называю изменение прогресса показывает:

-(void)downloadStart:(NSString*)fileUrl : (NSString*)name : (AVMVideoCell *) cell : (NSIndexPath *)path{ 

NSURL *URL = [NSURL URLWithString:fileUrl]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
NSString *fileName = [NSString stringWithFormat:@"%@.mp4",name]; //set full file name to save 
AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request]; //create download request 
[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSData *data = [[NSData alloc] initWithData:responseObject]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *pathToFile = [NSString stringWithFormat:@"%@/%@", [paths firstObject],fileName]; // path to 'Documents' 

    NSString *pathOfFile = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName]; 
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:pathOfFile append:NO]; 
    BOOL success = [data writeToFile:pathToFile atomically:YES]; 
    if(success){ 
     [self checkIfExists:name : cell :path]; 
    } 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"file downloading error : %@", [error localizedDescription]); 
    UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ]; 
    [alert show]; 
    cell.progressView.hidden = YES; 

}]; 
// Step 5: begin asynchronous download 
[downloadRequest start]; 
[downloadRequest setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { 

    [self progress:totalBytesRead :totalBytesExpectedToRead :cell :name : path]; //here I pass val1 and val 2 


    }]; 

} 

Когда я выбираю пункты в целях сбора, я собираю предметы их модели, получить каждый идентификатор и сделать массив URL-адресов, затем в for..in loop я передаю URL-адреса один за другим, а затем запускаю async-загрузку. Вы можете увидеть, как я загружаю и вызывается метод выполнения выше.

+0

Вы можете вставить весь код AVMVideoCell.m, пожалуйста? – Kujey

+0

@ Kujey уверен, см. Мое редактирование – vendettacore

ответ

1

мне нужно знать, если у вас есть проблемы повторного использования или выпуск модели.

Так первый попробовать это:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
... 

    if (![selectedIds.containsObject:selectedId]) 
    { 
     // Add the selected item into the array 
     [selectedIds addObject:selectedId]; 
     [selectedVideos addObject:selectedVideo]; 
     AVMVideoCell *collectionCell = (AVMVideoCell*)[collectionView cellForItemAtIndexPath:indexPath]; 
     NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)indexPath.row]; 
     if (![selecedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]] ) 
     { 
      [selecedCellsArray addObject:[NSString stringWithFormat:@"%ld",(long)indexPath.row]]; 
      collectionCell.selectedBG.hidden = NO; 
      collectionCell.selectedImg.hidden = NO; 
      [collectionCell setSelected:YES]; 
     } 
    } 
    else { 
    // Delete the selected item from the array 
    [selectedIds removeObject:selectedId]; 
    [selectedVideos removeObject:selectedVideo]; 
    AVMVideoCell *collectionCell = (AVMVideoCell*)[collectionView cellForItemAtIndexPath:indexPath]; 
    NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)indexPath.row]; 
    if ([selecedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]] ) 
    { 
     [selecedCellsArray removeObject:[NSString stringWithFormat:@"%ld",(long)indexPath.row]]; 
     collectionCell.selectedBG.hidden = YES; 
     collectionCell.selectedImg.hidden = YES; 
     [collectionCell setSelected:NO]; 
    } 
} 

и удалить делегат didDeselect.

Позвольте мне знать, что произойдет потом.

EDIT:

Ok попробовать это прямо сейчас:

// Lazy instantiation of the progressView 
- (UIProgressView *)progressView 
{ 
    if (!_progressView) 
    { 
     _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,0, 150.0f, 1.0f)]; 
     _progressView.trackTintColor = [UIColor colorWithWhite:255 alpha:0.5f]; 
     _progressView.progressTintColor = [UIColor whiteColor]; 
     _progressView.hidden = YES; 

     [self.contentView addSubview:_progressView]; 
    } 

    return _progressView; 
} 


// Here we remove the progressView on reuse 
-(void)prepareForReuse 
{ 
    [super prepareForReuse]; 

    [self.progressView removeFromSuperview]; 
    self.progressView = nil; 
} 

Также удалите то, что вы сделали с progressView с в методе cellForItemAtIndexPath.

+0

ничего не изменилось. кроме того, теперь я должен нажать 2 раза, чтобы выбрать/отменить выбор ячейки. Я уверен, что я повторно использую вопрос – vendettacore

+0

Является ли ваш прогрессview iboutlet? Где вы называете прогресс: val1: val2? – Kujey

+0

см. Мое редактирование 2 для объяснений – vendettacore

1

Вы можете создать класс для моделей ячеек, сохранить эти модели в массиве в свой viewController и использовать их для получения/установки всех состояний из/для ячеек.
Что-то вроде этого:

@interface CellModel : NSObject 
    @property(nonatomic) BOOL selected; 
    @property(nonatomic) NSUInteger progress; 
@end 

В ViewController:

@interface MyViewController() <UITableViewDataSource, UITableViewDelegate> 
    @property (nonatomic) NSArray* models; 
@end 
+0

, тогда мне нужно реализовать эту модель в моем пользовательском классе ячеек? – vendettacore

+0

@vendettacore да, вы можете передать эту модель каждой ячейке, когда вы ее деактивируете. Затем, если вам нужно обновить ход выполнения, вы можете захватить все видимые ячейки и обновить прогресс для тех, которые видны на экране. – Andy

+0

Я думаю, что лучше использовать отдельный файл для реализации CellModel –

 Смежные вопросы

  • Нет связанных вопросов^_^