iOS开发笔记之多点触控(四) 可靠的多点触控,为每个View分配唯一触摸对象
每个View需要分配有效的触摸以避免第三方触摸的干扰。实现方法如下
.h文件,接口定义两个变量
#import <UIKit/UIKit.h> @interface BBSViewController : UIViewController { UITouch *touch1; UITouch *touch2; } @end
.m文件,在touchesBegan里为view分配一个特定触摸对象(仅当它还未分配时)。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event //首次在屏幕上检测到触摸时调用 { NSLog(@"touchesBegan"); for (UITouch *touch in touches) { // NSLog(@" - %p",touch); //获取根视图内触摸点的point CGPoint touchPoint = [touch locationInView:self.view]; //约束两个view的活动范围 if (touch1 == nil && touchPoint.y < self.view.frame.size.height/2) { touch1 = touch; _view1.center = CGPointMake(touchPoint.x, _view1.center.y); }else if (touch2 == nil && touchPoint.y > self.view.frame.size.height/2) { touch2 = touch; _view2.center = CGPointMake(touchPoint.x, _view2.center.y); } } }
在touchesMoved方法里,忽略所有未绑定View的触摸
//以上对触摸进行了初始化,并未处理沿着屏幕移动的触摸。所以,只需要在touchesMoved方法里调用touchesBegan的处理方法来改写移动球拍的逻辑即可。 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event //如果触摸移动到了新的位置则会调用此方法 { NSLog(@"touchesMoved"); for (UITouch *touch in touches) { // NSLog(@" - %p",touch); // [self touchesBegan:touches withEvent:event]; CGPoint touchPoint = [touch locationInView:self.view]; if (touch == touch1) { _view1.center = CGPointMake(touchPoint.x, _view1.center.y); } else if (touch == touch2) { _view2.center = CGPointMake(touchPoint.x, _view2.center.y); } } }
及时释放已绑定了View的触摸,避免手指一离开屏幕就永久失去对View的控制。
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event//当触摸离开屏幕调用此方法 { NSLog(@"touchesEnded"); for (UITouch *touchin touches) { NSLog(@" - %p",touch); if (touch == touch1)touch1 = nil; else if (touch ==touch2) touch2 = nil; } } -(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event//如系统决定取消此次触摸,那可能就不调用touchesEnded方法了,在这种情况下会调用touchesCancelled方法 { NSLog(@"touchesCancelled"); // for (UITouch *touch in touches) // { // NSLog(@" - %p",touch); // }
[self touchesEnded:touches withEvent:event];
}
这样多余的触摸将不会影响现有的View的位置。
转载请注明原著来源:http://www.cnblogs.com/marvindev
下一篇介绍iOS开发笔记之摇动手势