在Cocoa中,代表觸摸對象的類是UITouch。當用戶觸摸屏幕後,就會產生相應的事件,所有相關的UITouch對象都被包裝在事件中,被程序交由特定的對象來處理。UITouch對象直接包括觸摸的詳細信息。
UITouch類中包含5個屬性:
window:觸摸產生時所處的窗口。由於窗口可能發生變化,當前所在的窗口不一定是最開始的窗口。 view:觸摸產生時所處的視圖。由於視圖可能發生變化,當前視圖也不一定時最初的視圖。 tapCount:輕擊(Tap)操作和鼠標的單擊操作類似,tapCount表示短時間內輕擊屏幕的次數。因此可以根據tapCount判斷單擊、雙擊或更多的輕擊。 timestamp:時間戳記錄了觸摸事件產生或變化時的時間。單位是秒。 phase:觸摸事件在屏幕上有一個週期,即觸摸開始、觸摸點移動、觸摸結束,還有中途取消。而通過phase可以查看當前觸摸事件在一個週期中所處的狀態。UIView類繼承了UIResponder類,要對事件作出處理還需要重寫UIResponder類中定義的事件處理函數。根據不同的觸碰狀態,程序會調用相應的處理函數,這些函數包括:
-(void) touchesBegan:(NSSet *)touches withEvents:(UIEvent *)event; //手在屏幕中
-(void) touchesMoved:(NSSet *)touches withEvents:(UIEvent *)event; //手在屏幕中移動
-(void) touchesEnded:(NSSet *)touches withEvents:(UIEvent *)event; //手離開屏幕
-(void) touchesCancelled:(NSSet *)touches withEvents:(UIEvent *)event; //無效 比如(接電話)
- 實例 一: 觸摸屏幕時 圖片跟着鼠標一起移動
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(20.0, 20.0, 30.0, 30.0)];
image.image = [UIImage imageNamed:@"QQ.png"];
image.tag = 100;
[self.view addSubview:image];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"手在屏幕中移動");
UITouch *touch = [touches anyObject];
UIImageView *view1 = (UIImageView *)[self.view viewWithTag:100];
CGPoint point = [touch locationInView:self.view];
CGRect frame = view1.frame;
frame.origin = point;
view1.frame = frame;
}
- 實例 二: 判斷 點擊屏幕次數 然後改變視圖元素
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"手離開屏幕");
UITouch *touch = [touches anyObject];
// tapCount 判斷 點擊屏幕次數
if (touch.tapCount == 1) {
self.view.backgroundColor = [UIColor whiteColor];
}
if (touch.tapCount == 2) {
self.view.backgroundColor = [UIColor redColor];
}
if (touch.tapCount == 3) {
self.view.backgroundColor = [UIColor yellowColor];
}
if (touch.tapCount == 4) {
self.view.backgroundColor = [UIColor grayColor];
}
}