ios的触摸事件-UITouch

版权所有,禁止匿名转载;禁止商业使用。

在ios开发的触摸事件中包括:


1.touchesBegan  触摸开始 在一次触摸事件中 只会执行一次


2.touchesMoved  触摸移动   在一次触摸事件中会执行多次


3.touchesEnded  触摸结束   再一次触摸事件中会执行一次


如果要调整控件 的位置可以使用 locationInView 和 previousLocationInView 计算移动的差值即可。


4.touchesCancelled 触摸取消(通常在接电话时会触发)


首先介绍一下小案例:移动红色方块的案例:


 

ios的触摸事件-UITouch

用到的触摸事件是:touchesMoved   设置红色方块的中心点为鼠标本地移动和与上次移动的点得差值,获得位移的偏移量。


#pragma mark - 在触摸方面开发时,只针对touches进行处理
#pragma mark - 触摸开始 在一次触摸事件中 只会执行一次
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  //NSLog(@"开始%@",touches);
}
#pragma mark - 触摸移动  在一次触摸事件中会执行多次
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
  //1.从nsset中取出touch对象
  //通常在单点触摸时。可以使用[touches anyObject] 取出UITouch对象
  UITouch *touch = [touches anyObject];
  //2.要知道手指触摸的位置
  CGPoint location = [touch locationInView:self.view];
  //2.1对位置进行修正
  
  CGPoint pLocation = [touch previousLocationInView:self.view];
  CGPoint deltaP = CGPointMake(location.x - pLocation.x, location.y-pLocation.y);
  CGPoint newCenter = CGPointMake(self.redView.center.x + deltaP.x, self.redView.center.y + deltaP.y);
  [self.redView setCenter:newCenter];
  NSLog(@"(%f,%f)---(%f,%f)",location.x,location.y,pLocation.x,pLocation.y);
}
//其中视图如果自己不进行设置则为单点触摸,所以可以使用 [touches anyObject] 获得uitouch对象,




这三句话是修正红色方块滚动时第一次移动时突然变化的问题,只要是平行移动的原理 ,距离上一次移动的距离。


previousLocationInView:是获得前一个坐标。
locationInView:获得当前的坐标。
CGPoint pLocation = [touch previousLocationInView:self.view];
CGPoint deltaP = CGPointMake(location.x - pLocation.x, location.y-pLocation.y);
CGPoint newCenter = CGPointMake(self.redView.center.x + deltaP.x, self.redView.center.y + deltaP.y);


0 0