1

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Nathan
  • 1,609
  • 4
  • 25
  • 42
  • 6
    This means that your view controller should probably be setting itself as a delegate for your view on view creation, and that your view should be calling this as a delegate method. – Linuxios Jan 21 '14 at 15:25
  • Take a look at: http://stackoverflow.com/questions/626898/how-do-i-create-delegates-in-objective-c – Retterdesdialogs Jan 21 '14 at 15:28
  • 1
    if you are passing completion block to subView from mainView, then in that block call that method. – santhu Jan 21 '14 at 15:28

2 Answers2

4

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

}
最白目
  • 3,505
  • 6
  • 59
  • 114
0

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

Community
  • 1
  • 1
brigadir
  • 6,874
  • 6
  • 46
  • 81