soleil
soleil

Reputation: 131

ios - addtarget to a button in another view controller

Why doesn't this work? I want the closeBtn in the new view controller to call a method called dismiss: in the current view controller.

NewViewController *newVC = [[NewViewController alloc] initWithNibName:@"NewViewController" bundle:[NSBundle mainBundle]];

[newVC.closeBtn addTarget:self action:@selector(dismiss:) forControlEvents:UIControlEventTouchUpInside];

The dismiss: method is never called in the current view controller. closeBtn is correctly set up as a property in NewViewController and linked in the .xib file.

Upvotes: 3

Views: 2308

Answers (2)

Apsara
Apsara

Reputation: 31

Create the object of the another controller and specify it in addTarget. Give the name of the method in the action parameter. i.e anotherController *obj; [button addTarget:obj action:@selector(MethodName) forControlEvents:UIControlEventTouchDown];

Upvotes: 3

mdominick
mdominick

Reputation: 1319

Generally, that is not a good way to deal with methods and UI elements.

However, you can do something like this, though it is ugly.

[yourButton addTarget:self action:@selector(yourButtonPressed:) forControlEvent:UITouchUpInside];

    - (void) yourButtonPressed:(id)sender {
    OtherVC* otherVC = [OtherVC alloc] initWithNibName@"NewViewController"] ...
    [otherVC theDesiredMethod];
   [otherVC release];
}

This works but is not really good you are probably better off moving the function into the proper VC.

Hope that helps.

Upvotes: -1

Related Questions