Access IBOutlet from another class

与世无争的帅哥 提交于 2019-12-11 17:11:14

问题


Hey I have two UIViewControllers. In the first one, there's an UIButton which contains an image. When the user then gets to my second ViewController, there are many buttons, which contain different images. So, when the user presses one button in my VC2, it should set the image from itself to the UIButton on my VC1.

I've already implemented the first VC by adding: #import "ViewController1.h" to the ViewController2.m before @interface ViewController2 ()

How can I do that? For example:

VC2:

- (IBAction)seaButton:(id)sender {
//Access the IBOutlet from VC1 and set the image of the Button like:

UIImage * seaBtnImage = [UIImage imageNamed:@"Sea.png"];
[buttonOutlet setImage:seaBtnImage forState:UIControlStateNormal];
}

Thanks!


回答1:


Step 1: In ViewController2.h create a property on VC2 to reference VC1:

#import "ViewController1.h"

@property (nonatomic, strong) ViewController1 *viewController1;

Step 2: When you create VC2 in VC1, set the property:

[viewController2 setViewController1:self];

Step 3: set the button image on ViewController2

[self.buttonVC2 setImage:[self.viewController1.buttonVC1 imageForState:UIControlStateNormal] forState:UIControlStateNormal];

Note: a better model is to provide a method on VC1 that returns the correct image. For example in VC1:

- (UIImage *)imageForButton {
    return [self.buttonVC1 imageForState:UIControlStateNormal];
}

and in VC2:

[self.buttonVC2 setImage[self.viewController1 imageForButton]];



回答2:


That's where delegates kick in. Define something like:

@protocol ButtonSelectionDelegate <NSObject>

- (void)didSelectButtonImage:(UIImage *)image;

@end

and implement it in VC1. Add the following property to VC2:

@property (nonatomic, weak) id<ButtonSelectionDelegate> delegate;

and set VC1 as VC2's delegate.

In the VC2's IBAction you will invoke the above didSelectButtonImage: method on the delegate by passing the locally selected image:

- (IBAction)seaButton:(id)sender
{
    UIImage *seaBtnImage = [UIImage imageNamed:@"Sea.png"];
    [self.delegate didSelectButtonImage:seaBtnImage];
}

In the VC1's didSelectButtonImage: you will update the outlet button image with the one VC2 provided by delegation:

- (void)didSelectButtonImage:(UIImage *)image
{
    [self.buttonOutlet setImage:image forState:UIControlStateNormal];
}


来源:https://stackoverflow.com/questions/25594183/access-iboutlet-from-another-class

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