[UIImageView CGImage]:无法识别的选择器发送到实例0x1783e5b00



这个问题已经连续3个小时了,我都要把我的Mac扔到房间的另一边了。

基本上,我试图传递一个UIImage给另一个视图控制器。我有这样的设置,当用户点击其中一个UIColectionViewCells时,它会将它们发送到另一个全屏UIImageView视图。我似乎无法弄清楚如何从ViewController1到ViewController2获取UIImage。

下面是我的一些代码。记住,我试图让这个UIImage selecteimage 从VC1到VC2。

<我> collectionView cellForItemAtIndexPath

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"GalleryCell";
    GalleryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    [cell.layer setBorderWidth:2.0f];
    [cell.layer setBorderColor:[UIColor whiteColor].CGColor];
    [cell.layer setCornerRadius:5.0f];
    UIImage *usingImage = [imageArray objectAtIndex:indexPath.row];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:usingImage];
    imageView.tag = 100;
    imageView.frame = CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height);
    [cell addSubview:imageView];
    return cell;
}

<我> collectionView didSelectItemAtIndexPath

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *selectedCell = [collectionView cellForItemAtIndexPath:indexPath];
    UIImage *selectedImage = (UIImage *)[selectedCell viewWithTag:100];
    [self performSegueWithIdentifier:@"GotoDetail" sender:nil];
}

可能是下面一行导致了这个问题:

UIImage *selectedImage = (UIImage *)[selectedCell viewWithTag:100];

当您使用viewWithTag:时,它将返回与单元格关联的UIImageView,而不是UIImage

你需要这样修改:

UIImageView *selectedImageView = (UIImageView *)[selectedCell viewWithTag:100];
UIImage *selectedImage = selectedImageView .image;

为了传递数据,将选中的图像存储在一个实例变量中(比如selectedImage),您需要像这样实现prepareForSegue::

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{       
        if ([segue.identifier isEqualToString:@"GotoDetail"])
        {
            YourDetailType *detailController = segue.destinationViewController;
            detailController.imageProperty= self.selectedImage;
        }   
}

你的代码有多个问题:

  1. 如果你没有从dequeue方法获得回调,你应该只在cell中添加一个图像视图。否则每次你回收一个单元格时,你都会给它添加另一个图像视图,所以过一会儿你就会在一个单元格上有几十个图像视图。

  2. 接下来,您不应该使用单元格作为存储图像的地方。您已经有了一个图像数组。使用它使用选定单元格的indexPath将图像传递给另一个视图控制器。

这导致了你的崩溃的原因,这一步2将修复:你正在转换一个图像视图到UIImage类型,这是错误的。

最后,要传递信息到你的细节视图控制器,添加一个属性selectedRow(一个整数)或selectedRowImage(一个UIImageView)到你的细节视图控制器。在prepareForSegue方法中,从segue获取目标视图控制器,将其转换为正确的类型,并使用所选单元格的indexPath设置属性。

[selectedCell viewWithTag:100]是一个UIImageView而不是一个UIImage, cast将不起作用

[(UIImageView *)[selectedCell viewWithTag:100]].image;

你可以尝试像这样获取UIImageViewUIImage引用。

…但是我同意Duncan C,你应该重新考虑如何获得图像,而不仅仅是从单元格的UIImageView中抓取它们。

最新更新