views:

727

answers:

2

Ola Folks,

I am looking for strategies, best practices and solutions to adding a custom class to the responder chain. This came about because I realized I was handling touch events the same way in several different applications. To make life easy, I wanted to move the functionality into a custom class and have that class become the first responder for touch events. Since my first several ideas did not work, I realized this wasn't going to be an ad-hoc issue I could address.

I have made several attempts based on different documents, posts, etc that I have read (which is why I'm not posting source right now). My most recent attempt derives from UIResponder and has a UIView member that stores a pointer to the current view.

Before I spent too much time on 'figuring it out', I wanted to see if anyone had any ideas.

So my question is 'how do I add a custom class to be the first responder, specifically to receive touch events'?

Thanx

-isdi-

A: 

Your solution sounds weird because UIView is itself a UIResponder.

If you have common event handling code, why not declare a category on UIView or UIResponder which you will then be able to access from all of your UIView (or UIResponder) subclasses including UIApplication, UIWindow and UIControl.

Roger Nolan
Roger,Because I didn't know what a category was until I read your post / answer.That worked. Thank you.
+1  A: 

Using Roger's suggestion, the solution I'm using looks like this:

Declaration (touchmyself.h)

#import <UIKit/UIViewController.h>
@interface UIViewController (TouchMyself)
    - (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event;
    - (void) touchesMoved: (NSSet *) touches withEvent: (UIEvent *) event;
    - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
    - (void) touchesCancelled: (NSSet*)touches withEvent: (UIEvent*) event;
@end

Implementation (touchmyself.m)

#import "touchmyself.h"
@implementation UIViewController (TouchMyself)
- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event
{
    // Do Stuff
}

...
@end

Consumer Declarations (some_view_controller.h)

@interface ViewSwitchBox : UIViewController 
{
    // Declare Stuff
}

After reading a couple of docs regarding categories, "iPhone SDK Application Development" chapter 1.5 put it into perspective.

-isdi-