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

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

屏幕上新建两个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 *touchintouches)

{//NSLog(@" - %p",touch);//获取根视图内触摸点的pointCGPoint 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 *touchintouches)

{//NSLog(@" - %p",touch);[self touchesBegan:touches withEvent:event];

}

}-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event//当触摸离开屏幕调用此方法{

NSLog(@"touchesEnded");for(UITouch *touchintouches)

{

NSLog(@"- %p",touch);

}

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

NSLog(@"touchesCancelled");for(UITouch *touchintouches)

{

NSLog(@"- %p",touch);

}

}

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

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

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航