Nathan
Nathan

Reputation: 1649

How Do I call a method from a view contained in a view controller ?

I have a UIViewController which contains a UIView Subclass, from the subclass I want to call a method defined in the UIViewController which contains it. I do not want to instantiate a new instance of the view controller, because it contains information that I need within the method I am attempting to call. Here is a diagram trying to further clarify:

(UIViewController) MainView --> has method updateView

(UIView) SubView ---> Has Button that plays animation and has completion block

I want to call UpdateView in the completion block

Upvotes: 1

Views: 764

Answers (2)

最白目
最白目

Reputation: 3644

I think you can set up a protocol in your Subview, which can be implemented by your ViewController

Your SubView.h

@class SubView;

@protocol SubViewDelegate <NSObject>
- (void)actionToPromoteToViewController: (NSString *)exampleString isSelected:(BOOL)exampleBool;
@end

Then, in your ViewController.h:

@interface MainViewController : UIViewController <SubViewDelegate>

and your ViewController.m, implement the method.

- (void)actionToPromoteToViewController: (NSString *)exampleString isSelected:(BOOL)exampleBool{
   // Method Implementation

}

Upvotes: 4

brigadir
brigadir

Reputation: 6942

For 'correct' implementation you need a reference to view controller in your UIView Subclass:

@interface UIViewSubclass : UIView
...
@property UIViewControllerSubclass *viewController;
@end

Then set this viewController reference to your view controller and use it in completion block.

If you want a local solution (and not to extend UIViewSubclass with property) take a look at this answer: https://stackoverflow.com/a/3732812/326017

Upvotes: 0

Related Questions