У меня есть UICollectionView
, который показывает некоторые данные из объекта CoreData. Этот объект имеет множество атрибутов, а один из них - image (трансформативный тип).Как работать с большими изображениями в iOS?
My UICollectionView
прокрутка не является гладкой. Я думаю, что причина - большие картинки в image атрибут (от 300 до 500k).
Вот код моего cellForItemAtIndexPath
:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *d = (AppDelegate *)[[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = @"cellRecipe";
RecipeCell *cell = (RecipeCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
cell.image.layer.borderColor = [UIColor blackColor].CGColor;
cell.image.layer.borderWidth = 1.0f;
Recipes *recipe = [recipesArray_ objectAtIndex:indexPath.item];
if ([recipe.isPaid integerValue] == 0)
[cell.freeImage setHidden:NO];
else [cell.freeImage setHidden:YES];
NSObject *object = [[NSUserDefaults standardUserDefaults] objectForKey:@"com.________.fullhomechef"];
if ([object isEqual:[NSNumber numberWithBool:YES]]) {
[cell.freeImage setHidden:YES];
}
if ([recipe.isFavorite integerValue] == 0)
[cell.favImage setImage:[UIImage imageNamed:@"toFavorite.png"]];
else [cell.favImage setImage: [UIImage imageNamed:@"toFavorite_.png"]];
if ([recipe.isFitness integerValue] == 1)
[cell.fitImage setHidden:NO];
else [cell.fitImage setHidden:YES];
if ([d.currLang isEqualToString:@"ru"])
[cell.recipeName setText: recipe.nameru];
else [cell.recipeName setText: recipe.nameen];
[cell.image setImage:recipe.image];
int difficulty = [recipe.difficulty intValue];
[cell.difficultyImage setImage: [mainTabController imageForRating:difficulty]];
return cell;
}
Я попытался прокомментировать линию [cell.image setImage:recipe.image];
но прокрутка еще
прерывистая.
Что я не так? Может быть, есть какой-то метод работы с большими изображениями? Cuz в предыдущих версиях я использовал изображения размером 50-70k.
P.S. Если я терпеливо прокручу его до конца, прокрутка станет более гладкой.
После ответа Гуто Araujo
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"cellRecipe";
RecipeCell *cell = (RecipeCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
cell.image.layer.borderColor = [UIColor blackColor].CGColor;
cell.image.layer.borderWidth = 1.0f;
Recipes *recipe = [fetchRecipes objectAtIndexPath:indexPath];
if ([recipe.isPaid integerValue] == 0) {
[cell.freeImage setHidden:NO];
}
else [cell.freeImage setHidden:YES];
if (wasPaid == YES) {
[cell.freeImage setHidden:YES];
}
if ([recipe.isFavorite integerValue] == 0)
[cell.favImage setImage:[UIImage imageNamed:@"toFavorite.png"] ];
else [cell.favImage setImage: [UIImage imageNamed:@"toFavorite_.png"]];
if ([recipe.isFitness integerValue] == 1)
[cell.fitImage setHidden:NO];
else [cell.fitImage setHidden:YES];
if ([d.currLang isEqualToString:@"ru"]) {
[cell.recipeName setText: recipe.nameru];
} else [cell.recipeName setText:recipe.nameen];
__weak typeof(self) weakSelf = self;
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
UIImage *image = recipe.image;
dispatch_async(dispatch_get_main_queue(), ^{
// Set via the main queue if the cell is still visible
if ([weakSelf.collectionView.indexPathsForVisibleItems containsObject:indexPath]) {
RecipeCell *cell =
(RecipeCell *)[weakSelf.collectionView cellForItemAtIndexPath:indexPath];
cell.image.image = image;
}
});
}];
[thumbnailQueue addOperation:operation];
int difficulty = [recipe.difficulty intValue];
[cell.difficultyImage setImage: [mainTabController imageForRating:difficulty]];
return cell;
}
Почему каждый раз приходится устанавливать новый 'MainTabController'? –
@MarceloFabri это простая функция, которая возвращает небольшое изображение в зависимости от ** уровня сложности ** от 1 до 5, и я уже инициализировал его в ** viewDidLoad ** – Romowski
Убедитесь, что размер изображения такой же, как ваша ячейка коллекция вид. Если размер изображения больше размера ячейки коллекции, тогда прокрутка не будет гладкой. – Manthan