iPhone タッチイベントに反応する

XCODEiPhoneアプリケーションを開発&リリースして便利な世の中を目指す!という目的のもと、今日は、タッチイベントについて学んで実装してみたので、それを書きます。

View上でタッチされた事に反応するには、UIResponderクラスのメソッドを利用する。

○ touchesBegan:withEvent:
 タッチイベントが始まったときに呼び出されるメソッド
○ touchesMoved:withEvent:
 ドラッグされ手いるときに呼び出されるメソッド 
○ touchesEnded:withEvent:
 タッチが終了したときに呼び出されるメソッド

UIResponderクラスはiPhoneの画面を作成する上でよく使うUIViewやUIViewController が継承している親クラスです。UIResponderクラスのメソッドを任意の子クラスでオーバーライドする事で、独自にタッチイベントを処理できるようです。
イメージ図:

実装例は以下の通りです。
<<タッチ開始>>

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject];
	CGPoint location = [touch locationInView:self.view];
	NSInteger taps = [touch tapCount];
	
	[super touchesBegan:touches withEvent:event];
	
	NSLog(@"タップ開始 %f, %f  タップ数:%d", location.x, location.y, taps);
}

タッチされた場所と回数を取得して、ログに出力しています。
マルチタッチを適切に処理したい場合には、引数のtouchesに格納されたUITouchイベントをマルチタッチ分処理する事で実現できます。



<<タッチ移動>>

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject];
	CGPoint oldLocation = [touch previousLocationInView:self.view];
	CGPoint newLocation = [touch locationInView:self.view];
	
	[super touchesMoved:touches withEvent:event];
	
	NSLog(@"指の動き:%f , %f から %f, %f", oldLocation.x, oldLocation.y, newLocation.x, newLocation.y);	
}

今回タッチ場所と前回タッチ場所を取得でき、ユーザーがどのような指の動きをしたかをログに出力しています。



<<タッチ終了>>

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {	
	UITouch *touch = [touches anyObject];
	CGPoint location = [touch locationInView:self.view];
	
	[super touchesEnded:touches withEvent:event];
	
	NSLog(@"タップ終了 %f, %f", location.x, location.y);	
}

指が画面から離れた際に呼び出されます。指が離れた場所を取得し、ログに出力します。



■ 注意事項
取得できる場所(CGPoint)は、左上からの座標になります。また画面全体ではなく、タッチイベントが発生したViewの左上からの座標となります。そのため、TabBarやNavigationBarがある場合にはその分Viewは小さくなり、小さくなったViewの左上からの座標がCGPointとして取得できます。

■ 最後に
画面の任意の場所のタッチイベントを取得して処理が出来るようになって、色々と出来て楽しいなと。指の軌跡を追って線を引き、手書き文字を描く。Graphicsと合わせて絵を描いてみる。色々と面白そうです。