gpt4 book ai didi

ios - 从文档目录获取图像到 Collection View

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:06:31 25 4
gpt4 key购买 nike

如何从文档目录中获取图像以填充 Collection View 。到目前为止,我根据我的日志将所有图像转储到每个单元格中,(或者至少图像名称打印在日志中)

首先,我从文档目录 filelist 中获取图像名称是 imageNames.png 的 NSMutable 数组

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];

if ([fileExt isEqualToString:@"png"]) {

[fileList addObject:filename];
}
}
NSLog(@"document folder content list %@ ",fileList);

这会在我的 NSMutsableArray fileList 中返回我的 png 文件名列表。然后我想把所有这些图片放到我的收藏 View 中

//set up cell from nib in viewDidLoad
UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
[self.appliancesCollectionView registerNib:cellNib forCellWithReuseIdentifier:@"cvCell"];


/////


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {


return fileList.count;
NSLog(@"collection view count is %@",fileList);

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

// Setup cell identifier
static NSString *cellIdentifier = @"cvCell";

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];


NSString *fileName = [fileList objectAtIndex:indexPath.row];
cell.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: fileName]];
NSLog(@"cell Bg image %@",fileList);

return cell;

}


The probelm is nothing shows up in my collection view cells

最佳答案

问题是 contentsOfDirectoryAtPath 返回相对文件路径。你需要绝对。应该使用如下内容:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; // NEW LINE 1

for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:@"png"]) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:filename]; // NEW LINE 2
[fileList addObject:fullPath]; // NEW LINE 3
}
}
NSLog(@"document folder content list %@ ",fileList);

关于ios - 从文档目录获取图像到 Collection View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21804129/

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