我有一本图像很少的字典。它的结构如下。
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 个部分,所有部分都有相同的图像(第 1 - 351 节.jpg、枕头 2.jpg、第 2 节 - 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)而不是键(例如bed)的部分。因此,我建议有序集合(NSArray)。检查此主题:苹果文档
您的主要问题似乎是这行代码:
UIImage *image = (UIImage*)[[(NSArray*)[self.imagesDictionary allValues] objectAtIndex:indexPath.row] objectAtIndex:indexPath.row];
因为
- 方法allValues不会按定义的顺序返回元素
- 您使用的是 indexPath.row 而不是 indexPath.section。