注:此范例是通过触摸事件移动view上的label
//隐藏键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self.view endEditing:YES];
}
//触摸开始
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
/*
timestamp 时间戳 phase 触摸状态 tapCount 点击次数 view 触摸视图
*/
//NSLog(@"at time:%lf", touch.timestamp);
//在指定视图上的点击位置
//CGPoint point = [touch locationInView:self.label];
//NSLog(@"%@", NSStringFromCGPoint(point));
}
//触摸移动,移动一直调用(不宜做耗时操作)
//此操作是对view上的label进行移动
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];//一般只有一个点击事件
//获取触摸视图
UIView *view = touch.view;
if (view == self.label) {//只对view视图上面的label进行拖动
//上次位置
CGPoint previousPoint = [touch previousLocationInView:self.view];
//本次位置
CGPoint currentPoint = [touch locationInView:self.view];
//得到偏移量
CGPoint offser = CGPointMake(currentPoint.x-previousPoint.x, currentPoint.y-previousPoint.y);
//控制移动
CGPoint center = view.center;
center.x += offser.x;
center.y += offser.y;
view.center = center;
}
}
//触摸结束
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
NSLog(@"触摸结束");
UITouch *touch = [touches anyObject];
NSLog(@"tapCount:%lu", touch.tapCount);//单位时间内点击的次数
}
//触摸被打断,如电话,一般不用此方法
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesCancelled:touches withEvent:event];
NSLog(@“触摸被取消”);
}