OBJECTIVE-C: 带有 UIImage 的 PushViewController 不工作

OBJECTIVE-C: PushViewController with UIImage doesn't work

我正在尝试将 UIImage 从第一个视图控制器传递到第二个视图控制器,但这并没有出现在第二个视图中。为什么?

我的代码在FirstController.m:

SecondController *second = (SecondController *)[self.storyboard instantiateViewControllerWithIdentifier:@"SBSecondController"];

second.imgCard.image = [UIImage imageNamed:@"image.png"];

[self.navigationController pushViewController:second animated:YES];

我的代码在SecondController.h:

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

我的代码在SecondController.m:

@implementation SecondController 

@synthesize imgCard;

你的第一行代码是错误的。初始化第二个视图控制器的正确方法是:

SecondController *second = (SecondController*)[self.storyboard instantiateViewControllerWithIdentifier:@"SBSecondController"];
second.imgCard.image = [UIImage imageNamed:@"image.png"];
...

如果您要在 ImageView 上设置的图像在您的 Assets.xcassets 或您的项目文件夹中,那么您不需要在 prapare 中为 sague 传递图像,只需按以下方式使用;

imgCard.image = [UIImage imageNamed:@"image.png"];

在FirstController.m中:

SecondController *second= (SecondController*)[self.storyboard instantiateViewControllerWithIdentifier:@"SBSecondController"];

second.imageVar = [UIImage imageNamed:@"image.png"];

[self.navigationController pushViewController:second animated:YES];

在SecondController.h中:

@property (nonatomic, strong) IBOutlet UIImageView *imgCard;
@property   UIImage *imageVar;

在SecondController.m中:

@implementation SecondController 

@synthesize imageVar,imgCard;

-(void)viewDidLoad{
[super viewDidLoad];
 imagCard.image = imageVar;
}

imgCard 将是 nil,直到加载第二个视图控制器的视图。在您按下视图控制器之前,这不会发生。直到需要时,才会创建视图控制器的视图,并且不会连接插座。

你有两个选择。

  • pushViewController 调用之后设置图像视图的图像(不确定这是否会导致视觉故障)
  • image 属性 添加到 SecondController 并设置它。在 SecondControllerviewDidLoad 中,设置 imgCard.image = self.image;