简体   繁体   English

在另一个视图的UIImageView上设置图像

[英]Set Image On Another View's UIImageView

I am trying to create a sort of 'settings' page, and I am having a hard time switching the background image of my original view. 我正在尝试创建一种“设置”页面,我很难切换原始视图的背景图像。 The code, so far, is: 到目前为止,代码是:

-(IBAction)switchBackground:(id)sender {
ViewController *mainView = [[ViewController alloc] initWithNibName:nil bundle:nil];
mainView.displayedImage.image = [UIImage imageNamed:@"image.png"];;
}

Perhaps I can get some pointers? 也许我可以得到一些指示?

Thanks, all. 谢谢,所有。

You are creating a new mainView object each time you call switchBackground method. 每次调用switchBackground方法时都要创建一个新的mainView对象。 You must change the background of an existing object to see the change happen. 您必须更改现有对象的背景才能看到更改发生。

From your code it is hard to say where switchBackground method is located. 从您的代码中很难说出switchBackground方法的位置。 ViewController ? ViewController

If it is located in the view controller then all you have to do is: 如果它位于视图控制器中,那么您所要做的就是:

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

EDIT 编辑

As per your comment. 根据你的评论。

When you want to change the image of an object of class A from class B you can do it in two different ways: 如果要从B类更改A类对象的图像,可以通过两种不同的方式完成:

1. Through reference to an object 1.通过参考一个对象

this is the settings initializer which on creation gets the pointer to your existing mainView 这是设置初始化程序,在创建时获取指向现有mainView的指针

@property(nonatomic,assign)ViewController *mainView;

- (id)initWithMainViewController:(ViewController*)vc {
    self = [super init];
    if (self) {
        self.mainView = vc;
    }
    return self;
}

-(IBAction)switchBackground:(id)sender {
    mainView.displayedImage.image = [UIImage imageNamed:@"image.png"];
}

2. By posting local notification through NSNotificationCenter. 2.通过NSNotificationCenter发布本地通知。

-(IBAction)switchBackground:(id)sender {
      [[NSNotificationCenter defaultCenter] postNotificationName: @"changeImage" object: [UIImage imageNamed:@"image.png"]];
}

Now in your ViewController listen to the notification and react 现在在你的ViewController中听取通知并做出反应

in the init method in ViewController 在ViewController的init方法中

- (id)initWithMainViewController:(ViewController*)vc {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeImage:) name:@"changeImage" object:nil];
    }
    return self;
}

-(void)changeImage:(NSNotification*)notification{
    self.displayedImage.image = (UIImage*) notification.object;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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