简体   繁体   中英

Assigning image from another View Controller class

I have a unassigned UIImageView in one View Controller class. I want to assign it using UIImage ImageNamed:@"examplePic.png" from another View Controller class's .m file

Here is my code -

Class1.h
//The class with the unassigned UIImageView
@property (strong, nonatomic) IBOutlet UIImageView *myImage;
//The UIImageView is connected to the @property


Class2.m
//
Class1 *class1 = [[Class1 alloc] init];
class1.myImage.image = [UIImage imageNamed:@"examplePic.png"];

It looks like your UIImageView is not being initialized before you attempt to set its image property. Try the following:

class1.myImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"examplePic.png"]]

The problem is that your UIImageView has not been initialised yet. To fix this:

Add a new property for an UIImage:

@property (nonatomic) UIImage *imageForImageView;

When initialising your UIViewController which will be pushed onto the stack try this:

UIViewController *someViewController = [[UIViewController alloc] initWithNibName:@"SomeNibName" bundle:nil];
someViewController.imageForImageView = image;
[self.navigationController pushViewController:someViewController animated:YES];

Then in your viewDidLoad of someViewController you can assign imageForImageView as image to your UIImageView .

This way you ensure that the UIImageView actually is in memory when assigning an UIImage to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM