从 UIButton 中的另一个 class 调用方法

Call method from another class in a UIButton

我有一个自定义 UITableViewCell,有一个 class 链接到它,叫做 customCell.m。 (我没有使用 xib。)在单元格中有一个按钮。有没有办法在 mainVC.m 文件上创建按钮操作,与 customCell.m 相对?

更新

这是我尝试实现的代码。我所做的是,我从 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'

您正在调用 myMethod,但该方法实际上是 myMethod: 并将发送者作为参数。尝试更改:

[mainVC myMethod];

至:

[mainVC myMethod:sender];

此外,您当前作为参数传递给 myMethod: 的任何发件人,都不属于 mainVC 的 table 视图,因为您正在创建一个全新的 CategorieViewController 实例来执行方法调用,它的 table 从未被加载。

假设MainVC是vis​​ible view controller,可以改成:

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

至:

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

使用加载的 table 视图获取当前 MainVC 实例。