Search code examples
iosobjective-cxcodeuibuttoniboutlet

Access IBOutlet from another class


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!


Solution

  • 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]];