gpt4 book ai didi

ios - 如何将图像从NSDictionary获取到UICollectionView iOS?

转载 作者:行者123 更新时间:2023-12-01 18:12:19 24 4
gpt4 key购买 nike

我有一本词典,图片很少。它的结构如下。
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;
}

关于ios - 如何将图像从NSDictionary获取到UICollectionView iOS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28235491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com