iOS开发笔记之多点触控(四) 可靠的多点触控,为每个View分配唯一触摸对象
2014-01-16 23:50
302 查看
每个View需要分配有效的触摸以避免第三方触摸的干扰。实现方法如下
.h文件,接口定义两个变量
.m文件,在touchesBegan里为view分配一个特定触摸对象(仅当它还未分配时)。
在touchesMoved方法里,忽略所有未绑定View的触摸
及时释放已绑定了View的触摸,避免手指一离开屏幕就永久失去对View的控制。
这样多余的触摸将不会影响现有的View的位置。
转载请注明原著:http://blog.csdn.net/marvindev
下一篇介绍iOS开发笔记之摇动手势
.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://blog.csdn.net/marvindev
下一篇介绍iOS开发笔记之摇动手势
相关文章推荐
- iOS开发笔记之多点触控(三) 调用UITouch对象方法——locationInView,多点移动多个对象
- IOS开发学习笔记027-UITableView 使用模型对象
- iOS开发笔记之多点触控(一)处理触摸的4个方法
- iOS开发笔记--UIImageView的属性之animationImages详解
- IOS开发笔记33-UITableView(1)
- iOS开发笔记>> 设置scrollView的contentSize能在viewDidLoad里设置么,为什么?
- 《iOS开发笔记—WebView与MKWebView》
- 2011斯坦福大学iOS应用开发教程学习笔记(第八课)viewController生命周期
- iOS开发笔记--TableView详解(2)
- ios开发笔记(三)—— UITableView的性能优化
- 我的ios开发笔记(1)tableview+nav
- IOS开发笔记16-类与对象
- 斯坦福大学iOS应用开发教程学习笔记(第八课)viewController生命周期
- UITextField类对象左视图leftView无效--iOS开发
- IOS开发学习笔记(四)——使用TableView
- IOS开发学习笔记033-UIScrollView
- iOS开发笔记- cell里放textView根据输入的文字动态改变textView以及cell高度
- IOS开发笔记10-Object-C中的对象
- iOS开发笔记--UITableView入门
- IOS开发笔记(Swift):UITableView表格视图的静态使用