I have a custom class of a UIView I've made inside my viewcontroller. I want to make this class re-usable and so don't want to build it to work just with this 1 viewcontroller. Because of this, I think the best way of telling my viewcontroller that the user has interacted with the class is to somehow make my own UIControlEvent. Maybe something like:
[customClass addTarget:self action:@selector(whatIWantToHappen) forControlEvents:UIControlEventWhatever];
I don't know much about doing this though, any suggestions on this?
You could do this by subclassing UIControl
, which inherits from UIView, but provides some additional methods for handling targets and actions. Have a look at the constants, perhaps one of the predefined control events already fits your bill. Otherwise, you could define your own events in the range provided by UIControlEventApplicationReserved
, you should however never prefix your own things with UI...
, that 'namespace' is reserved for UIKit.
In addition to the answer by omz, you may get a compiler warning when doing this:
[self addTarget:self action:@selector(selector:) forControlEvents:CustomControlEvent];
The compiler doesn't like the custom value being used for the last parameter, which is of type UIControlEvents
, so it throws a warning.
I did this:
enum CustomControlEvent : UIControlEvents
{
CustomControlEventWHATEVER = UIControlEventApplicationReserved
};
typedef enum CustomControlEvent CustomControlEvent;
Behold! No more warnings.
I found this notation in this StackOverflow answer.
N.B. For UIControlEvents
, I am strongly avoiding the use of any unavailable values, so I only use the UIControlEventApplicationReserved
value.
Additionally, the typedef relinquishes the need to type 'enum' every time and is customary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With