·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOS开发笔记之多点触控(三)调用UITouch对象方法——locationInView,多点移动多个对象

iOS开发笔记之多点触控(三)调用UITouch对象方法——locationInView,多点移动多个对象

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

屏幕上新建两个view,实现两个手指在屏幕上移动两个view,通过规则约束两个view的活动范围。

关键在于调用UITouch对象的方法——lacationInView。此方法返回View的相对于根视图的触摸位置。返回值是一个CGPoint类型,是一个包含X坐标和Y坐标的结构体。我让两个view在屏幕上下两个半区水平移动。利用CGPointMake来快速初始化新的CGPoint结构体。

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.multipleTouchEnabled = TRUE;
    // Do any additional setup after loading the view, typically from a nib.
    _view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 40, 40, 40)];
    _view1.backgroundColor = [UIColor blueColor];
    [self.view addSubview:_view1];
    
    _view2 = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 60, 40, 40)];
    _view2.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:_view2];

}

-(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 (touchPoint.y < self.view.frame.size.height/2)
        {
            _view1.center = CGPointMake(touchPoint.x, _view1.center.y);
        }else
        {
            _view2.center = CGPointMake(touchPoint.x, _view2.center.y);
        }
    }
}

//以上对触摸进行了初始化,并未处理沿着屏幕移动的触摸。所以,只需要在touchesMoved方法里调用touchesBegan的处理方法来改写移动球拍的逻辑即可。
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event //如果触摸移动到了新的位置则会调用此方法
{
    NSLog(@"touchesMoved");
    for (UITouch *touch in touches)
    {
//        NSLog(@" - %p",touch);
        [self touchesBegan:touches withEvent:event];
    }

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event//当触摸离开屏幕调用此方法
{
    NSLog(@"touchesEnded");
    for (UITouch *touch in touches)
    {
        NSLog(@" - %p",touch);
    }

}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event//如系统决定取消此次触摸,那可能就不调用touchesEnded方法了,在这种情况下会调用touchesCancelled方法
{
    NSLog(@"touchesCancelled");
    for (UITouch *touch in touches)
    {
        NSLog(@" - %p",touch);
    }

}

下图为两个view可以分别沿着水平方向移动

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

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