如何从文档目录中获取图像以弹出集合视图。到目前为止,我根据我的日志将所有图像转储到每个单元格中(或者至少图像名称打印在日志中)
首先从文档目录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
答案 0 :(得分:2)
问题是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);
答案 1 :(得分:1)
您需要使用imageWithContentsOfFile:代替imageNamed:
NSString * filePath = [[NSBundle mainBundle] pathForResource:<imageNameWithoutExtansion>ofType:<fileExtansion>];
cell.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageWithContentsOfFile: filePath]];