我拥有的是一组文件名。这是我用来填充集合视图单元格的代码。
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ReuseID" forIndexPath:indexPath];
NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/DrawnImage"];
NSArray *contentOfDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:NULL];
NSString *fileName = [contentOfDirectory objectAtIndex:indexPath.item];
NSString *path = [dataPath stringByAppendingPathComponent:fileName];
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageView *cellImageView = cell.collectionImageView;
cellImageView.image = image;
return cell;
}
图像在单元格中正确显示。我想要做什么,当我单击一个单元格时,该单元格中的图片必须在详细视图控制器中全屏显示。
我试过这个。
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"])
{
NSIndexPath *selectedIndexPath = [[self.collectionView indexPathsForSelectedItems] objectAtIndex:0];
NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/DrawnImage"];
NSArray *contentOfDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:NULL];
NSString *fileName = [contentOfDirectory objectAtIndex:selectedIndexPath.item];
NSString *pathToImage = [dataPath stringByAppendingPathComponent:fileName];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage];
UIImageView *backgroundImageView = [[UIImageView alloc] initWithImage:image];
DetailViewController *dvc = [segue destinationViewController];
dvc.finalImage = sender;
NSLog(@"%@", backgroundImageView);
}
}
finalImage 是 Detail View Controller 中的 UIImageView。单击其中一个单元格时出现运行时错误。我究竟做错了什么 ?
编辑
这是我现在拥有的代码。
集合视图控制器.h
@property (nonatomic, retain) UIImage *sendImage;
集合视图控制器.m
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"])
{
NSIndexPath *selectedIndexPath = [[self.collectionView indexPathsForSelectedItems] objectAtIndex:0];
NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/DrawnImage"];
NSArray *contentOfDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:NULL];
NSString *fileName = [contentOfDirectory objectAtIndex:selectedIndexPath.item];
NSString *pathToImage = [dataPath stringByAppendingPathComponent:fileName];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage];
DetailViewController *dvc = [segue destinationViewController];
dvc.passedInImage = image;
image = dvc.passedInImage;
}
}
DetailViewController.h
@property (weak, nonatomic) IBOutlet UIImageView *finalImage;
@property UIImage *passedInImage;
细节视图控制器.m
-(void)viewDidAppear:(BOOL)animated {
self.finalImage.image = passedInImage;
}