Search code examples
iosobjective-cuibuttonactioncustom-cell

Call method from another class in a UIButton


I have a custom UITableViewCell with a class linked to it called customCell.m. (I didn't use xib.) In the cell there is a button. Is there a way to create the buttons action on the mainVC.m file, as apposed to customCell.m?

Update

Here is the code I tried implementing. What I did is, I called a method from mainVC.m.

CustomCell.m

- (IBAction)myButton:(id)sender
{
    CategorieViewController *mainVC = [[CategorieViewController alloc] init];
    [mainVC myMethod];
}

MainVC.m

- (void)myMethod:(id)sender
{
    UITableViewCell *clickedCell = (UITableViewCell *)[[[sender superview] superview] superview];
    NSIndexPath *clickedButtonPath = [self.myTableView indexPathForCell:clickedCell];

    NSLog(@"%@", clickedButtonPath);
}

CategorieViewController myMethod]: unrecognized selector sent to instance 0x7fd2dbd52a00

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CategorieViewController myMethod]: unrecognized selector sent to instance 0x7fd2dbd52a00'


Solution

  • You're calling myMethod, but the method is actually myMethod: and takes the sender as a parameter. Try changing:

    [mainVC myMethod];
    

    to:

    [mainVC myMethod:sender];
    

    Also, any sender you currently pass to myMethod: as a parameter, won't belong to mainVC's tableview yet because you're creating a brand new CategorieViewController instance to perform the method call and its table has never been loaded.

    Assuming MainVC is the visible view controller, you can change:

    CategorieViewController *mainVC = [[CategorieViewController alloc] init];
    

    to:

    UINavigationController *nav = (UINavigationController*)self.window.rootViewController;
    CategorieViewController *mainVC = (CategorieViewController*)nav.visibleViewController;
    

    to get the current the current MainVC instance with the loaded tableview.