느린 로딩 이미지는 내 collectionView의 고르지 못한 느린 효과 뒤에있었습니다. 나는 하루 종일 다양한 Q 글을 읽고있다. &. 이 문제를 해결하는 가장 좋은 방법은 cellForItemAtIndexPath에 필요한 데이터를 사전로드하여 필요한 정보를 얻을 수있게하는 것입니다.UICollectionView에서 어떻게 내부에서 사용할 cellForItemAtIndexPath 외부의 데이터를 미리로드 할 수 있습니까?
나는 이것을 어떻게 할 수 있는지 잘 모르겠습니다. 내 백엔드로 구문 분석을 사용하고 있지만 확실한 예가 주어진다면이를 수행하는 방법을 알아낼 수 있을지 확신합니다. 지금까지 본 것부터 데이터를 가져 오는 별도의 방법이 필요합니다.
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [[self objects] count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
NSArray *people = [self objects];
static NSString *CellIdentifier = @"Cell";
VAGGarmentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: CellIdentifier forIndexPath:indexPath];
PFObject *current;
current = [people objectAtIndex:indexPath.item];
PFFile *userImageFile = current[@"image"];
[userImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
UIImage *image = [UIImage imageWithData:imageData];
[[cell contentView] setContentMode: UIViewContentModeScaleAspectFit];
[[cell imageView] setImage:image];
}];
[[cell title] setText:[current valueForKey:@"title"]];
[[cell price] setText:[NSString stringWithFormat: @"£%@", [current valueForKey:@"price"]]];
return cell;
}
그래서 어쩌면 cellForItemAtIndexPath 그 메서드를 호출하고 무엇을 필요로하는지 취할 필요가 : 여기
는 코드입니다. 데이터가 이미 사용 가능하므로 cellForItemAtIndexPath 메소드에로드 할 필요가 없으며 셀이 즉시 채워집니다.
제안 사항과 예제를 제공해주십시오.
이미지를 확인하는 것이 좋을 것이라고 말했고, 존재하지 않는다면 자리 표시자를 제공하고, 존재한다면 설정합니다. 위의 코드가 변경되었습니다.
업데이트 :
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
NSArray *people = [self objects];
static NSString *CellIdentifier = @"Cell";
VAGGarmentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: CellIdentifier forIndexPath:indexPath];
PFObject *current;
current = [people objectAtIndex:indexPath.item];
PFFile *userImageFile = current[@"image"];
[userImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error)
{
if (!image) {
[[cell imageView] setImage:[UIImage imageNamed:@"placeholder.png"]];
} else {
image = [UIImage imageWithData:imageData];
//resize image
CGSize destinationSize = CGSizeMake(158,187);
UIGraphicsBeginImageContext(destinationSize);
[image drawInRect:CGRectMake(0,0,destinationSize.width, destinationSize.height)];
//New image
UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Optimise image
NSData *imageDataCompressed = UIImageJPEGRepresentation(newImage, 0.4f);
// NSLog(@"Image Size %@", NSStringFromCGSize(newImage.size));//log size of image
NSLog(@"%@", [current valueForKey:@"title"]);
[[cell imageView] setImage:[UIImage imageWithData:imageDataCompressed]];
}
}
}];
[[cell title] setText:[current valueForKey:@"title"]];
[[cell price] setText:[NSString stringWithFormat: @"£%@", [current valueForKey:@"price"]]];
return cell;
}
플레이스 홀더가 잘 표시하지만 남아, 이미지가 그래서 내 세포가를 반영 할 수로드 된 경우 어떻게 알 수 있습니까?
감사합니다. 친절하게 생각합니다.
업데이트 :
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
NSArray *people = [self objects];
static NSString *CellIdentifier = @"Cell";
VAGGarmentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: CellIdentifier forIndexPath:indexPath];
[cell.activityIndicator startAnimating];
PFObject *current;
current = [people objectAtIndex:indexPath.item];
PFFile *userImageFile = current[@"image"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:userImageFile.url, indexPath.item]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataDontLoad
timeoutInterval:6.0];
[cell.imageView setImageWithURLRequest:urlRequest
placeholderImage:[UIImage imageNamed:@"placeholder.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
//resize image
CGSize destinationSize = CGSizeMake(158,187);
UIGraphicsBeginImageContext(destinationSize);
[image drawInRect:CGRectMake(0,0,destinationSize.width, destinationSize.height)];
//New image
UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Optimise image
NSData *imageDataCompressed = UIImageJPEGRepresentation(newImage, 0.4f);
cell.imageView.image = [UIImage imageWithData:imageDataCompressed];
NSLog(@"Image Size %@", NSStringFromCGSize(newImage.size));//log size of image
[cell.activityIndicator stopAnimating];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Failed to download image: %@", error);
}];
return cell;
}
최근 업데이트 :
변경 가능한 배열 후 NSMutableDictionary parse.com에 저장 데이터를 얻는 방법을 설정한다. 나는 옷의 이미지에 제목, 가격 및 URL을 저장합니다.
- (void)grabDataFromCloud
{
self.model = [NSMutableArray array];
for (PFObject *object in [self objects]) {
PFFile *imageFile = [object valueForKey:@"image"];
NSURL *url = [NSURL URLWithString:imageFile.url];
NSMutableDictionary *newObject = [NSMutableDictionary dictionaryWithDictionary:@{@"title": [object valueForKey:@"title"], @"price": [object valueForKey:@"price"], @"imageUrl": url}];
[[self model] addObject:newObject];
}
}
이것은 내 cellForItemsAtIndexPath 메소드에서 호출됩니다.
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
[self grabDataFromCloud];
static NSString *CellIdentifier = @"Cell";
VAGGarmentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: CellIdentifier forIndexPath:indexPath];
[cell.activityIndicator setHidden:YES];
NSMutableDictionary* d = [self.model objectAtIndex:indexPath.item];
cell.title.text = d[@"title"];
cell.price.text = [NSString stringWithFormat:@"£%@", d[@"price"]];
if (d[@"image"]) {
cell.imageView.image = d[@"image"];
} else { // if not, download it
cell.imageView.image = nil;
dispatch_queue_t backgroundQueue = dispatch_queue_create("test", 0);
dispatch_async(backgroundQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:d[@"imageUrl"]];
UIImage* img = [UIImage imageWithData:data];
d[@"image"] = img;
dispatch_async(dispatch_get_main_queue(), ^{
//causes crash Assertion failure in -[UICollectionView _endItemAnimations],
// /SourceCache/UIKit/UIKit-2935.137/UICollectionView.m:3687
// [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
});
});
}
return cell;
}
나는 이것을 작동 시키려고 노력 해왔다. 캐싱과는 별도로 작업하고있다. cachepolicy를 NSURLRequestReturnCacheDataElseLoad로 설정 했는데도 이미지가 계속 다시 다운로드됩니다. 이미지가 다운로드 된 것처럼 보이지만 스크롤 할 때 나는 여전히 도려내 기 효과를 얻습니다. – LondonGuy