ios 用UItouch实现简单动画
我也是个小白,最近看了些UITouch的知识,自己写了个简单的动画。
将view像手指滑动的方向移动,实现view的切换,效果图如下:
通过简单的UItouch的偏移量计算就可以实现该动画,
视图定义这种基础的东西就不说了,UItouch是不需要绑定视图的,不过获取的坐标是某一个视图的内的相对坐标,这个取决你用哪个view,我这里用的是tapview。
[touch previousLocationInView:_tapView];
获取手指刚触摸到屏幕时候的坐标
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
_startPoint=[touch previousLocationInView:_tapView];
}
获取手指离开屏幕时候的坐标
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"touchClick");
UITouch *touch=[touches anyObject];
CGPoint stopPoint=[touch locationInView:_tapView];
通过计算开始坐标和结束坐标的差值,判断偏移量和便宜方向。但是结束的时候touch不一定和开始坐标在一个视图上,这就产生了相对坐标不一致的情况,可以通过
UIView *touchView=[touch view];
if(touchView==self.view)
{
stopPoint=[touch locationInView:self.view];
_startPoint.x+=_firstCardView.frame.origin.x;
_startPoint.y+=_firstCardView.frame.origin.y;
}
判断结束坐标所在的视图,在通过相应的修改,使得坐标在一个参数上。核心代码就这些,以下是关于该动画完整的代码
-(void)addView{
UIView *firstCardView1=[[UIView alloc]initWithFrame:CGRectMake(MAINWINDOWWIDTH/5, MAINWINDOWHEIGHT/5, MAINWINDOWWIDTH*0.6, MAINWINDOWHEIGHT*0.6)];
UILabel *showLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 200, 20)];
showLabel.text=[NSString stringWithFormat:@"这是第%d个卡片",_lableFlag];
showLabel.textColor=[UIColor purpleColor];
[firstCardView1 addSubview:showLabel];
firstCardView1.backgroundColor=[UIColor grayColor];
[self.view addSubview:firstCardView1];
NSTimer *time=[[NSTimer alloc]init];
[self.view addSubview:_firstCardView];
time=[NSTimer scheduledTimerWithTimeInterval:0.5 repeats:NO block:^(NSTimer * _Nonnull timer) {
[_firstCardView removeFromSuperview];
[_tapView removeFromSuperview];
_firstCardView=firstCardView1;
[self.view addSubview:_tapView];
}];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
_startPoint=[touch previousLocationInView:_tapView];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"touchClick");
UITouch *touch=[touches anyObject];
CGPoint stopPoint=[touch locationInView:_tapView];
UIView *touchView=[touch view];
if(touchView==self.view)
{
stopPoint=[touch locationInView:self.view];
_startPoint.x+=_firstCardView.frame.origin.x;
_startPoint.y+=_firstCardView.frame.origin.y;
}
if(_startPoint.x-stopPoint.x>=3||_startPoint.x-stopPoint.x<=-3||_startPoint.y-stopPoint.y<=-3||_startPoint.y-stopPoint.y>=3)
{
[UIView animateWithDuration:0.5 animations:^{
_firstCardView.frame=CGRectMake((stopPoint.x-_startPoint.x)*25+MAINWINDOWWIDTH/5, (stopPoint.y-_startPoint.y)*25+ MAINWINDOWHEIGHT/5, MAINWINDOWWIDTH*0.6, MAINWINDOWHEIGHT*0.6);
}];
_lableFlag++;
[self addView];
}
}