iOS基础之触摸事件处理
现在的手机都是触屏的,当我们在手机上使用一个软件的时候,我们都需要去触摸它。在iOS中,一个UITouch对象表示一个触摸,一个UIEvent对象表示一个事件。事件对象中包含与当前多点触摸序列相对应的所有触摸对象,还可以提供与特定试图或窗口相关联的触摸对象。
触摸事件的处理方法:
@implementation TouchView //触摸的三个时间阶段的方法 //开始 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"%s %d",__FUNCTION__,__LINE__); self.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0]; // //记录屏幕的宽和高 // CGFloat screenWidth = [[UIScreen mainScreen]bounds].size.width; // CGFloat screenHeight = [[UIScreen mainScreen]bounds].size.height; // int minX = (int)(self.frame.size.width/2); // int maxX = (int)(screenWidth - self.frame.size.width/2); // int minY = (int)(self.frame.size.height/2); // int maxY = (int)(screenHeight) - minY; // // CGPoint newCenter = CGPointMake(0, 0); // newCenter.x = arc4random() % (maxX - minX + 1) + minX; // newCenter.y = arc4random() % (maxY - minY + 1) + minY; // self.center = newCenter; } //移动 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"%s %d",__FUNCTION__,__LINE__); //获取触摸在屏幕上的手指对象 UITouch *touch = [touches anyObject]; //获取手指之前在屏幕上的位置 CGPoint previousP = [touch previousLocationInView:self]; //获取手指在现在屏幕上的位置 CGPoint currentP = [touch locationInView:self]; CGPoint newCenter = CGPointMake(0, 0); newCenter.x = self.center.x + (currentP.x - previousP.x); newCenter.y = self.center.y + (currentP.y - previousP.y); self.center = newCenter; self.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0]; } //结束 -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"%s %d",__FUNCTION__,__LINE__); } @end