[英]Vast memory required with UICollectionView images set from NSDictionary
[英]How to fetch images from NSDictionary to UICollectionView iOS?
我有一本很少图片的字典。 它的结构如下。
NSDictionary
|__ bed
| |__ 351.jpg
| |__ 352.jpg
|__ pillow
| |__ pillow1.png
|__ pillow2.png
我试图将其添加到colloectioview
,如下所示。
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return self.imagesDictionary.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [[[self.imagesDictionary allValues] objectAtIndex:section] count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
// Setup cell identifier
static NSString *cellIdentifier = @"ImageCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
UIImage *image = (UIImage*)[[(NSArray*)[self.imagesDictionary allValues] objectAtIndex:indexPath.row] objectAtIndex:indexPath.row];
recipeImageView.image = image;
[cell addSubview:recipeImageView];
// Return the cell
return cell;
}
当我运行此代码时,我得到了2个部分,并且所有部分都具有相同的图像(section1-351.jpg,枕头2.jpg,section2-351.jpg,枕头2.jpg)。 我怎样才能解决这个问题。
提前致谢!
这里的问题很可能源于NSDictionary不是有序容器的事实。 如果要按索引从中选择项目,则需要先对键进行排序,然后再将它们编入索引。 尝试这样的事情:
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return self.imagesDictionary.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
NSArray* sortedSections = [[self.imagesDictionary allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSString* key = sortedSections[section];
NSArray* images = self.imagesDictionary[key];
return images.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
// Setup cell identifier
static NSString *cellIdentifier = @"ImageCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
NSArray* sortedSections = [[self.imagesDictionary allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSString* key = sortedSections[[indexPath indexAtPosition: 0]];
NSArray* images = self.imagesDictionary[key];
UIImage *image = (UIImage*) images[[indexPath indexAtPosition: 1]];
recipeImageView.image = image;
[cell addSubview:recipeImageView];
// Return the cell
return cell;
}
在这种情况下,我不建议您将项目存储在NSDictionary上,因为您需要搜索具有索引(例如0)而不是键(例如床)的部分。 因此,我建议使用有序集合(NSArray)。 检查此主题: Apple文档
您的主要问题似乎是以下代码行:
UIImage *image = (UIImage*)[[(NSArray*)[self.imagesDictionary allValues] objectAtIndex:indexPath.row] objectAtIndex:indexPath.row];
因为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.