Iphone 制作自定义类';s按钮触发父类

Iphone 制作自定义类';s按钮触发父类,iphone,objective-c,ios,uiviewcontroller,Iphone,Objective C,Ios,Uiviewcontroller,我有一个名为“MainViewController”的UIViewController,它使用自定义类“CustomController”来控制它的一个子视图。自定义类在代码中实例化UIButtons。如何让这些按钮触发MainViewController中的方法?我认为委派是实现这一点的方法 使用如下方法定义协议CustomControllerDelegate内部CustomController.h,例如: - (void) customControllerButtonPressed(id)s

我有一个名为“MainViewController”的
UIViewController
,它使用自定义类“CustomController”来控制它的一个子视图。自定义类在代码中实例化
UIButton
s。如何让这些按钮触发MainViewController中的方法?

我认为委派是实现这一点的方法

  • 使用如下方法定义协议
    CustomControllerDelegate
    内部
    CustomController.h
    ,例如:

    - (void) customControllerButtonPressed(id)sender; // BTW: you can use `CustomController` instead of `id` if you make a forward declaration for this class
    
  • 添加代理属性并在
    .m
    文件中合成它

    @property (assign) id<CustomControllerDelgate> delegate;
    
  • MainViewController
    中,使其符合指定的协议,并按如下方式设置CustomController委托:

    CustomViewController *customVC = [[CustomViewController alloc] init];
    customVC.delegate = self;
    
  • 现在,当按下按钮时,将调用指定方法的
    MainViewController
    实现


  • 我相信,如果父类方法在标头中声明,您可以访问它们…@CodaFi这是真的,但是该类需要了解MainViewController,并且您有一个紧密耦合,这通常是不可取的(特别是如果它是双向的)。如果我是他,我无论如何都会使用类方法,因为它更干净,如果需要,他可以从类方法调用实例方法。此外,当他的类被实例化时,它将自动实例化超类,从而保证他的方法的成功。
    CustomViewController *customVC = [[CustomViewController alloc] init];
    customVC.delegate = self;