特定のビューに対するタッチの取得だったら、touchesBegan:withEvent:などをオーバーライドすれば良いのですが、画面全体となるとどうでしょう。
画面全体に対してユーザーがタッチしているかを取得したい
ユーザーが一定時間画面を触っていなかったら、スクリーンセーバー的なものを出す、というような用途を想定しています。そういう場合に、画面全体に対してユーザーが何か操作しているかを知りたい場合、どうしたら良いのかを調べました。
今回の場合は、touchesBegan:withEvent:では、対象のビューをオーバーライドできないので、使えません。
調べたところ、UIGestureRecognizerが使えそうでした。
UIGestureRecognizer Class Reference
UIWindowに対してタッチを検出
UIGestureRecognizerで検出する対象のビューを、UIWindowにすることで画面全体へのタッチを取得することができます。
たとえば、アプリ起動時にアプリのUIWindowに対してUITapGestureRecognizerを適用します。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UIWindow *window = [[[UIApplication sharedApplication] delegate] window]; UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(detectedTapGesture:)]; [window addGestureRecognizer:tapGestureRecognizer]; return YES; } |
UITapGestureRecognizerは、UIGestureRecognizerのサブクラスで、タップを検出するものです。
画面がタップされるとUITagGestureRecognizerによって、指定したセレクタが呼び出されますので、ここでタッチ座標を取得するなどします。
- (void)detectedTapGesture:(UITapGestureRecognizer *)sender { UIWindow *window = [[[UIApplication sharedApplication] delegate] window]; CGPoint point = [sender locationOfTouch:0 inView:window]; NSLog(@"tap point: %@", NSStringFromCGPoint(point)); } |
シミュレータで試してみます。
テキトーに触ってみると、座標が出力されています。
2014-04-09 19:30:39.377 test[55956:90b] tap point: {70, 161.5} 2014-04-09 19:30:40.091 test[55956:90b] tap point: {182.5, 238} 2014-04-09 19:30:40.819 test[55956:90b] tap point: {209, 329} 2014-04-09 19:30:41.371 test[55956:90b] tap point: {87.5, 384} 2014-04-09 19:30:41.995 test[55956:90b] tap point: {249.5, 95.5} |
タップ以外の操作の検出
タップ以外の操作を検出するために、UIGestureRecognizerのサブクラスがたくさん用意されています。
[window addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(detectedGesture:)]]; [window addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(detectedGesture:)]]; [window addGestureRecognizer:[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(detectedGesture:)]]; [window addGestureRecognizer:[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(detectedGesture:)]]; [window addGestureRecognizer:[[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(detectedGesture:)]]; |
複雑なUIGestureRecognizerを定義したら隠しコマンドみたいなの作れそうですね・・・。