尝试从 didSelectCellAtIndex 加载图片到新的 ViewController [英] trying to load a picture into new ViewController from didSelectCellAtIndex

查看:20
本文介绍了尝试从 didSelectCellAtIndex 加载图片到新的 ViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 CollectionView,在 didSelectItemAtIndexPath 方法中,我实例化了一个新的 ViewController,在 ViewController 上设置 String 属性来保存图像的名称.然后在新的 ViewController 中的 viewDidLoad 或 viewDidAppear 方法中,我尝试使用 vc.imageName 属性设置图像.

I have a CollectionView and in the didSelectItemAtIndexPath method I have instantiating a new ViewController, setting the String property on the ViewController to hold the image's name. And then in the viewDidLoad OR the viewDidAppear method in the new ViewController I am trying to set the image using the vc.imageName property.

代码如下:

// collection.m


    -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        ViewController *vc = [[ViewController alloc] init];

        NSString *imageName = [colouringPhotos objectAtIndex:indexPath.row];
        vc.imageName = imageName;
        [self presentViewController:vc animated:YES completion:nil];
    }


// ViewController.h

@property (nonatomic, strong) NSString * imageName;

//ViewController.m

@property (strong, nonatomic) IBOutlet UIImageView *lineImageView;

-(void) viewDidAppear:(BOOL)animated{
    self.lineImageView.image = [UIImage imageNamed:self.imageName];
}

但是图片没有显示.我已经在 ImageView 上设置了背景颜色,以检查它是否显示在新的 ViewController 中,我可以看到它,但图像从不显示在 UIImageView 中.

But the image doesn't show. I have set the background colour on the ImageView to check that it is being displayed in the new ViewController and I can see it but the image never displays within the UIImageView.

推荐答案

您可以使用 Segue 来显示下一个视图控制器.假设您使用ShowNextViewController"作为 Segue 的标识符,您可以使用 prepareForSegue:sender: 来设置目标视图控制器的 imageName 属性:

You could use a Segue to show the next view controller. Assuming you use "ShowNextViewController" as the identifier for your Segue, you could use prepareForSegue:sender: to set the imageName property of the destination view controller:

- (void)prepareForSegue:(nonnull UIStoryboardSegue *)segue sender:(nullable id)sender {

    if ([segue.identifier isEqualToString:@"ShowNextViewController"]) {
        ViewController *destination = (ViewController *)segue.destinationViewController;
        NSIndexPath *selectedIndex = [[self.collectionView indexPathsForSelectedItems] firstObject];
        destination.imageName = self.colouringPhotos[selectedIndex.row];
    }
}

如果您在设置 segue 时遇到问题,请参阅 此 iOS 开发者库文档了解更多信息.

If you have trouble setting up the segue, see this iOS Developer Library document for more information.

另外,请参阅 prepareForSegue:sender: 方法的更多信息,请参阅 rel="nofollow">UIViewController 类参考.

Also, see the UIViewController Class Reference for more information on the prepareForSegue:sender: method.

这篇关于尝试从 didSelectCellAtIndex 加载图片到新的 ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆