thewarri0r9 thewarri0r9 - 1 year ago 62
iOS Question

iOS cannot add action to the button from different view controller

I have a

ViewController 1
in which I have a button, which calls
ViewController 2
using a present view controller. I have added an action to Button which is in
ViewController 2
. But Button doesn't call that action when clicked.
my code is:

To display
ViewController 2

- (void)viewDidLoad{
[super viewDidLoad];

ViewController2 * addShot = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil];
[addShot.addShotButton addTarget:self action:@selector(submitShot:) forControlEvents:UIControlEventTouchUpInside];

- (IBAction)addShotButtonTapped:(id)sender{
[addShot setModalPresentationStyle:UIModalPresentationPopover];
[addShot setModalTransitionStyle:UIModalTransitionStyleCoverVertical];

UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:addShot];
[self presentViewController:nav animated:YES completion:nil];

Everything works fine but
submitShot action
never gets called. Suggestions?

Answer Source

Add you protocol in your ViewController2.h like this

@protocol  ViewController2Delegate <NSObject>

-(void) submitShotTapped;


before your @interface

and in your interface declare a property of it.

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

Always use weak property for your delegate.

On action of your submitShot add call this delegate method like this

- (IBAction) submitShot:(id)sender {
    [self.delegate submitShotTapped];

Now in your ViewController1 declare that delegate like this

@interface TagDetails ()<ViewController2Delegate>

Now while creating your object of ViewController2 assign this delegate to self of ViewController1 like this

ViewController2 * addShot = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil];
addShot.delegate = self;

Then implement that delegate method in ViewController1 like this

-(void) submitShotTapped {
     //Shot button tapped on ViewController2

This is how you can use delegate, also remove the targets which you have added on button.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download