iphone开发-UIView Touch事件
怎样捕获手指的触摸事件呢?
理论不说了,在开发文档里面说的很详细。就说说实现。
其实就是要重写实现三个函数,如下:
touch开始时会调用touchesBegan
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouches = [event allTouches];
UITouch *touch = [touches anyObject];
NSLog(@"touch view++++++%@", [touch view]);
// [touch view]获得当前touch的view
//[allTouches count]获得当前touch的是否是多触摸,如果 [allTouches count] == 1就不是多触摸。
switch ([allTouches count]) {
case 1: {
// potential pan gesture
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
[self setPanningModeWithLocation:[touch locationInView:self]];
} break;
case 2: {
// potential zoom gesture
UITouch *touch0 = [[allTouches allObjects] objectAtIndex:0];
UITouch *touch1 = [[allTouches allObjects] objectAtIndex:1];
CGFloat spacing =
[self eucledianDistanceFromPoint:[touch0 locationInView:self]
toPoint:[touch1 locationInView:self]];
[self setZoomingModeWithSpacing:spacing];
} break;
default:
[self resetTouches];
break;
}
}
//是指触摸移动时,调touchesMoved
#define ZOOM_IN_TOUCH_SPACING_RATIO (0.75)
#define ZOOM_OUT_TOUCH_SPACING_RATIO (1.5)
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//获取当前touch的点
CGPoint location = [touch locationInView:self];
switch ([allTouches count])
{
case 1:
{
}
break;
case 2:
{
UITouch *touch0 = [[allTouches allObjects] objectAtIndex:0];
UITouch *touch1 = [[allTouches allObjects] objectAtIndex:1];
CGFloat spacing =
[self eucledianDistanceFromPoint:[touch0 locationInView:self]
toPoint:[touch1 locationInView:self]];
CGFloat spacingRatio = spacing / lastTouchSpacing_;
if (spacingRatio >= ZOOM_OUT_TOUCH_SPACING_RATIO){
[self zoomIn];
}
else if (spacingRatio <= ZOOM_IN_TOUCH_SPACING_RATIO) {
[self zoomOut];
}
}
break;
default:
break;
}
}
//结束时调用touchesEnded
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
实现这三个方法,根据需要添加相应的代码,完成想要的功能。