iosobjective-cuiviewmultiple-views

Multiple UIViews, passing methods


I have two UIView contained in a UIViewController - firstView and secondView - that I initialize pragmatically. I have a UILabel in the firstView, and a UIButton in the secondView. I would like the button in the second view to change the label in the first view. In the implementation file of the second view I have the following code:

- (void) changeLabel: (UIButton *) sender{
    firstView *view = [[firstView alloc] init];
    view.label.text = @"Changed Text";
}

However I figured out that the above method just initializes a new class of firstView and does not link to the existing UIView. How can I change properties of firstView from within secondView?


Solution

  • Create properties in your view controller's header file for the views:

    @property (nonatomic, retain) UIView *firstView;
    @property (nonatomic, retain) UILabel *label;
    

    When you create the view and label assign them to the properties:

    self.firstView = // create your view here
    
    self.label = // create your label here
    

    Create a button property on your UIView object so you can access it later:

    @property (nonatomic, retain) UIButton *button;
    

    Then in your view controller file, when you create everything, access the view's button property and add a target, like this:

    [firstView.button addTarget:self action:@selector(changeLabel) forControlEvents:UIControlEventTouchUpInside];
    

    Then you can simply have the method your button calls be like this:

    - (void)changeLabel {
        self.label.text = @"Changed Text.";
    }