Iphone 创建我自己的uicontrol事件并触发它?

Iphone 创建我自己的uicontrol事件并触发它?,iphone,objective-c,notifications,Iphone,Objective C,Notifications,我在viewcontroller中创建了UIView的自定义类。我想使这个类可重用,所以不想构建它来只与这个1 viewcontroller一起工作。因此,我认为告诉我的viewcontroller用户已与类交互的最好方法是以某种方式创建我自己的uicontrol事件。可能是这样的: [customClass addTarget:self action:@selector(whatIWantToHappen) forControlEvents:UIControlEventWhatever];

我在viewcontroller中创建了UIView的自定义类。我想使这个类可重用,所以不想构建它来只与这个1 viewcontroller一起工作。因此,我认为告诉我的viewcontroller用户已与类交互的最好方法是以某种方式创建我自己的uicontrol事件。可能是这样的:

[customClass addTarget:self action:@selector(whatIWantToHappen) forControlEvents:UIControlEventWhatever];

虽然我不知道怎么做,但对此有什么建议吗?

您可以通过子类化
UIControl
来做到这一点,该子类继承自UIView,但提供了一些处理目标和操作的附加方法。看一看,也许其中一个预定义的控制事件已经符合您的要求。否则,您可以在
UIControlEventApplicationReserved
提供的范围内定义您自己的事件,但是您不应该在您自己的事件前面加上
UI…
,即“名称空间”是为UIKit保留的。

除了omz提供的答案外,执行此操作时您可能会收到编译器警告:

[self addTarget:self action:@selector(selector:) forControlEvents:CustomControlEvent];
编译器不喜欢最后一个参数使用的自定义值,该参数的类型为
UIControlEvents
,因此会抛出警告

我这样做:

enum CustomControlEvent : UIControlEvents
{
    CustomControlEventWHATEVER  =   UIControlEventApplicationReserved
};
typedef enum CustomControlEvent CustomControlEvent;
瞧!没有更多的警告

我在答案中找到了这个符号

注意:对于
UIControlEvents
,我强烈避免使用任何不可用的值,因此我只使用
UIControlEventApplicationReserved


此外,typedef放弃了每次键入“enum”的需要,这是惯例。

Timo,这可能有点晚,但UIControlEventApplicationReserved不是一个值,它是一个位掩码(它甚至被注释为“可供应用程序使用的范围”)。它定义为0x0F000000,因此您应该使用0x01000000、0x02000000、0x04000000和0x08000000作为自定义事件。此行
枚举CustomControlEvent:UIControlEvents
给我一个错误,指出uicontrol事件是无效的基础事件type@rounak我写这篇文章已经很久了。。。这个解决方案可能已经失败了!