Make image accessible from other ViewController

痞子三分冷 提交于 2020-01-05 12:09:23

问题


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:


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;


来源:https://stackoverflow.com/questions/30960053/make-image-accessible-from-other-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!