Make image accessible from other ViewController

2019-08-15 18:37发布

I just want to know the code for making an image called profpic accessible to all other ViewControllers that I make or intend to make. I have read many posts on global variables, public variables, and other suggestions that have yet to work. If it helps, I am specifically using this to display an image from ViewControllerA as the background for ViewControllerB.

1条回答
Anthone
2楼-- · 2019-08-15 19:04

You can use a singleton class and put the UIImage on it. Set it in ViewControllerA and get it in ViewControllerB

@interface MySingleton : NSObject 

@property (nonatomic, strong) UIImage *myImage;

+ (MySingleton *)sharedInstance;

@end


@implementation MySingleton

#pragma mark Singleton Methods

+ (MySingleton *)sharedInstance {
    static MySingleton *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
return sharedInstance;
}

- (id)init {
  if (self = [super init]) {
  }
  return self;
}
@end

To access myImage

// set myImage in ViewControllerA
MySingleton *mySingleton = [MySingleton sharedInstance];
mySingleton.myImage = [UIImage imageNamed:@"imageName"];

// get my image in ViewControllerB
MySingleton *mySingleton = [MySingleton sharedInstance];
myImageView.image = mySingleton.myImage;
查看更多
登录 后发表回答