[英]Get images from documents directory to 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文件名的列表。 然后我想将所有这些图像放入收藏夹视图
//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);
您需要使用imageWithContentsOfFile:而不是imageNamed:
NSString * filePath = [[NSBundle mainBundle] pathForResource:<imageNameWithoutExtansion>ofType:<fileExtansion>];
cell.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageWithContentsOfFile: filePath]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.