iPhoneやiPad等のiOSでタッチやタップといったイベントを検知して処理する方法をまとめました。UIWindowクラスを継承し、そのクラスのタッチイベント関連のメソッドを実装することで実現できるようです。タッチイベントに関する4つのメソッドと、それらが呼ばれるタイミングを次にまとめました。
- touchesBegan:画面に指が触れた時
- touchesMoved:画面に指が触れた状態で指を移動させた時
- touchesEnded:画面から指が離れた時
- touchesCancelled:タッチイベントがキャンセルされた時
touchesCancelledは、例えば画面に指が触れている状態でHOMEボタンを押した時などに呼ばれます。また、各イベントは引数にタッチされた位置(touches)と、イベントの呼び出し元情報(event)などを持ちます。
タッチ検出サンプルプログラム
まず、UIWindowクラスを継承したBaseWindowクラスを作成しました。そして、上記の4つのメソッドをBaseWindowに実装し、シングルタップの制限の下で検出位置をログに表示するようにしました。BaseWindowを呼ぶクラスはAppDelegateです。(iPhoneアプリ開発環境を整える - XCode4のインストールからHello Worldまで -でのソースコードを書き換えました。)
AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
UIWindow* _window;
}
@property (strong, nonatomic) UIWindow *window;
@end
AppDelegate.m
#import "AppDelegate.h"
#import "BaseWindow.h"
@implementation AppDelegate
@synthesize window = _window;
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
_window = [[BaseWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
[self.window makeKeyAndVisible];
return YES;
}
@end
BaseWindow.h
#import <UIKit/UIKit.h>
@interface BaseWindow : UIWindow {
CGPoint location;
}
@end
BaseWindow.m
#import "BaseWindow.h"
@implementation BaseWindow
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
location = [[touches anyObject] locationInView:self];
NSLog(@"touchesBegan: (x, y) = (%.0f, %.0f)", location.x, location.y);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
location = [[touches anyObject] locationInView:self];
NSLog(@"touchesMoved: (x, y) = (%.0f, %.0f)", location.x, location.y);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
location = [[touches anyObject] locationInView:self];
NSLog(@"touchesEnded: (x, y) = (%.0f, %.0f)", location.x, location.y);
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
location = [[touches anyObject] locationInView:self];
NSLog(@"touchesCanceled: (x, y) = (%.0f, %.0f)", location.x, location.y);
}
@end
実行結果
指を画面に着ける→指移動→指を離す→再度指を画面に着ける→HOMEボタン押下の順に実行すると、次のようなログが出力されました。
2012-07-26 00:55:18.879 HelloWorld[7342:f803] touchesBegan: (x, y) = (126, 197) 2012-07-26 00:55:20.061 HelloWorld[7342:f803] touchesMoved: (x, y) = (127, 198) 2012-07-26 00:55:20.178 HelloWorld[7342:f803] touchesMoved: (x, y) = (127, 199) 2012-07-26 00:55:20.459 HelloWorld[7342:f803] touchesEnded: (x, y) = (127, 199) 2012-07-26 00:55:50.219 HelloWorld[7342:f803] touchesBegan: (x, y) = (127, 199) 2012-07-26 00:55:53.575 HelloWorld[7342:f803] touchesCanceled: (x, y) = (127, 199)
0 件のコメント:
コメントを投稿