ViewがTapされた時を検知するときはdelegate使うんだぜ!!
tapされた事を検知する処理はよく使う処理なので定型化したい。
次のようにDelegateして使うViewを用意しておく
#import <Foundation/Foundation.h> @protocol MyViewTapDelegate; @interface MyViewTap : UIView { id <MyViewTapDelegate> tapDelegate; } @property (nonatomic, assign) id <MyViewTapDelegate> tapDelegate; - (void)handleSingleTap:(UITouch *)touch; - (void)handleDoubleTap:(UITouch *)touch; - (void)handleTripleTap:(UITouch *)touch; @end @protocol MyViewTapDelegate <NSObject> @optional - (void)view:(UIView *)view singleTapDetected:(UITouch *)touch; - (void)view:(UIView *)view doubleTapDetected:(UITouch *)touch; - (void)view:(UIView *)view tripleTapDetected:(UITouch *)touch; @end
#import "MyViewTap.h" @implementation MyViewTap @synthesize tapDelegate; - (id)init { if ((self = [super init])) { self.userInteractionEnabled = YES; } return self; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.userInteractionEnabled = YES; } return self; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; NSUInteger tapCount = touch.tapCount; switch (tapCount) { case 1: [self handleSingleTap:touch]; break; case 2: [self handleDoubleTap:touch]; break; case 3: [self handleTripleTap:touch]; break; default: break; } [[self nextResponder] touchesEnded:touches withEvent:event]; } - (void)handleSingleTap:(UITouch *)touch { if ([tapDelegate respondsToSelector:@selector(view:singleTapDetected:)]) [tapDelegate view:self singleTapDetected:touch]; } - (void)handleDoubleTap:(UITouch *)touch { if ([tapDelegate respondsToSelector:@selector(view:doubleTapDetected:)]) [tapDelegate view:self doubleTapDetected:touch]; } - (void)handleTripleTap:(UITouch *)touch { if ([tapDelegate respondsToSelector:@selector(view:tripleTapDetected:)]) [tapDelegate view:self tripleTapDetected:touch]; } @end
上記のViewを別のViewにかぶせて使います。
- (id)initWithFrame:(CGRect)frame { // Tap view for background _tapView = [[MyViewTap alloc] initWithFrame:frame]; _tapView.tapDelegate = self; _tapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; _tapView.backgroundColor = [UIColor blackColor]; [self addSubview:_tapView]; ... } - (void)handleSingleTap:(CGPoint)touchPoint { // singleTapの場合はこのメソッドが呼ばれる } - (void)handleDoubleTap:(CGPoint)touchPoint { // DoubleTapの場合 } - (void)handleTripleTap:(CGPoint)touchPoint { // TripleTapの場合 }
ユーザーから見るとベースとなっているViewの前に透明なViewが存在していて、
TapがSingleかDoubleかTripleかという事だけを判定して残りの処理はベースとなっているViewに委譲しています。
擬人化するとたぶんこんな感じじゃないかな?
BaseView「おう、ユーザーが選択した処理がAなのかBなのかCなのかを俺に言ってくれ。ただし、それに対する結果は俺が決める。どんな処理するかの決定権は俺に委譲してくれだぜ!!」
TapView「あいー」
間違ってたらだれかがきっと通りすがってコメントしてくれるさ。