Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make my own UIControlEvent, and trigger it?

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?

like image 286
Andrew Avatar asked May 26 '11 15:05

Andrew


2 Answers

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.

like image 178
omz Avatar answered Nov 09 '22 07:11

omz


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.

like image 40
Timo Avatar answered Nov 09 '22 08:11

Timo