
UIViewにはタッチについての4つのメソッドが定義されている。
タッチ開始
- (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
UIViewのサプクラスを作って、この4つをオーバーライドすれば実装できちゃう!

実装サンプルとしてTouchViewクラスをつくってみる
@interface TouchView: UIView{
UILabel* label;
}
@end
@implementation TouchView
- (id)init{
self = [super init];
label = [[UILabel alloc]init];
label.frame = CGRectMake(10, 50, 300, 20);
[self addSubview:label];
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch* touch = (UITouch*)[touches anyObject];
CGPoint pt = [touch locationInView:self];
label.text = [NSString stringWithFormat:@"began [%f, %f]", pt.x, pt.y];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch* touch = (UITouch*)[touches anyObject];
CGPoint pt = [touch locationInView:self];
label.text = [NSString stringWithFormat:@"ended [%f, %f]", pt.x, pt.y];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch* touch = (UITouch*)[touches anyObject];
CGPoint pt = [touch locationInView:self];
label.text = [NSString stringWithFormat:@"moved [%f, %f]", pt.x, pt.y];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch* touch = (UITouch*)[touches anyObject];
CGPoint pt = [touch locationInView:self];
label.text = [NSString stringWithFormat:@"cancelled [%f, %f]", pt.x, pt.y];
}
@end
touches変数にUITouchクラスが格納されてる。
今回はシングルタッチのみ対応なので、必ず1個だけ。
[touches anyObject]で格納されているオブジェクトがあれば取得できる。
タッチイベントからビュー内座標を取得して画面に表示するようにしてある。
これを画面にセットすれば完成!
TouchView* touch = [[TouchView alloc]init];
touch.frame = CGRectMake(0, 0, 320, 480);
[oya addSubview:touch];
