觸摸事件UITouch的應用,觸摸事件uitouch
因為UIView或者UIViewController都是繼承與UIResponder ,所以都有UITouch這個事件。當使用者點擊螢幕的時候,會產生觸摸事件。
通過UITouch事件,可以監聽到開始觸摸、觸摸移動過程、觸摸結束以及觸摸打斷四個不同階段的狀態,在這些方法中,我們能夠擷取到很多有用的資訊,比如觸摸點的座標、觸摸的手指數、觸摸的次數等等,下面通過一個小例子來說明一下。
詳細代碼如下:
/* 定義屬性 */@interface ViewController (){ CGPoint _startPoint; //開始點擊的點 CGPoint _endPoint; //結束點擊的點 UILabel *_label1; //顯示當前觸摸的狀態的標籤 UILabel *_label2; UILabel *_label3; UILabel *_label4; UIImageView *_imageView; //笑臉圖片}/* 觸摸事件UITouch的系列方法如下所示 <一>到<四> */#pragma mark <一> 當一個或多個手指觸碰螢幕時,發送touchesBegan:withEvent:訊息-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ _label1.text = @"觸摸 開始 "; //1. 首先擷取觸控螢幕幕的手指 UITouch * touch = [touches anyObject]; //2. 點擊的當前點的座標 CGPoint point = [touch locationInView:self.view]; _label2.text = [NSString stringWithFormat:@"當前點得座標:x=%.1f, y=%.1f",point.x,point.y]; //4. 擷取觸控螢幕幕的次數 int tapCount = touch.tapCount; //5. 擷取觸控螢幕幕的手指根數 int fingerCount = touches.count; _label3.text = [NSString stringWithFormat:@"觸控螢幕幕次數為%i, 觸摸的手指數為%i",tapCount,fingerCount]; //6. 當前視圖預設只支援單點觸摸 如果想添加多點觸摸 必須開啟多點觸摸模式 self.view.multipleTouchEnabled = YES; //7.1. 得到開始點擊的點,得到最後點擊的點,計算一下,看看做了什麼操作 _startPoint = [touch locationInView:self.view]; _label4.text = @"";}#pragma mark <二> 當一個或多個手指在螢幕上移動時,發送touchesMoved:withEvent:訊息-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ _label1.text = @"觸摸 move..."; CGPoint point = [[touches anyObject] locationInView:self.view]; _label2.text = [NSString stringWithFormat:@"當前點得座標:x=%.1f, y=%.1f",point.x,point.y];}#pragma mark <三> 當一個或多個手指離開螢幕時,發送touchesEnded:withEvent:訊息-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ _label1.text = @"觸摸 結束"; CGPoint point = [[touches anyObject] locationInView:self.view]; //3. 判斷是否進入了圖片範圍內 if (CGRectContainsPoint(_imageView.frame, point)) { _label2.text = @"停留在笑臉圖片範圍內"; } else { _label2.text = @"停留在笑臉圖片外面"; } //7.2 計算開始到結束位移量 float distanceX = fabsf(point.x - _startPoint.x); //擷取手指縱向移動的位移量 float distanceY = fabsf(point.y - _startPoint.y); _label4.text = [NSString stringWithFormat:@"x位移了%.1f,y方向位移了%.1f",distanceX,distanceY]; _startPoint = CGPointZero;}#pragma mark <四> 當觸摸序列被諸如電話呼入這樣的系統事件打斷所意外取消時,發送touchesCancelled:withEvent:訊息-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{ _label1.text = @"觸摸 取消";}