首页 > 其他 > 详细

iOS开发笔记之多点触控(四) 可靠的多点触控,为每个View分配唯一触摸对象

时间:2014-02-09 15:35:52      阅读:358      评论:0      收藏:0      [点我收藏+]

每个View需要分配有效的触摸以避免第三方触摸的干扰。实现方法如下

.h文件,接口定义两个变量

bubuko.com,布布扣
#import <UIKit/UIKit.h>

@interface BBSViewController : UIViewController
{
    UITouch *touch1;
    UITouch *touch2;
}

@end
bubuko.com,布布扣

.m文件,在touchesBegan里为view分配一个特定触摸对象(仅当它还未分配时)。

bubuko.com,布布扣
-(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);
        }
    }
}
bubuko.com,布布扣

在touchesMoved方法里,忽略所有未绑定View的触摸

 

bubuko.com,布布扣
//以上对触摸进行了初始化,并未处理沿着屏幕移动的触摸。所以,只需要在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);
        }
    }
}
bubuko.com,布布扣

 

及时释放已绑定了View的触摸,避免手指一离开屏幕就永久失去对View的控制。

bubuko.com,布布扣
-(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:toucheswithEvent:event];
}
bubuko.com,布布扣

这样多余的触摸将不会影响现有的View的位置。

转载请注明原著来源:http://www.cnblogs.com/marvindev

下一篇介绍iOS开发笔记之摇动手势

 

iOS开发笔记之多点触控(四) 可靠的多点触控,为每个View分配唯一触摸对象

原文:http://www.cnblogs.com/marvindev/p/touches4.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!