Я уже задал тот же вопрос о сохранении нажатого состояния кнопки, и я подумал, что должен делать то же самое, чтобы сохранить состояние состояния на ячейках, но мои попытки не увенчались успехом.Сохранить состояние выполнения 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-загрузку. Вы можете увидеть, как я загружаю и вызывается метод выполнения выше.
Вы можете вставить весь код AVMVideoCell.m, пожалуйста? – Kujey
@ Kujey уверен, см. Мое редактирование – vendettacore