demo 地址https://github.com/liranhao/PhotoViewerTest
图片查看器弹出动画和下滑关闭查看器动画,仅供想学习这类动画的朋友学习
效果
可以使用模态的方式弹出查看器controller,为了使present的VC和当前VC在同一层级
我们设置一下这个参数
TestViewController *test = [[TestViewController alloc] init];
test.modalPresentationStyle = UIModalPresentationOverCurrentContext;//具体意思参考https://blog.csdn.net/tianweitao/article/details/80314598
test.definesPresentationContext = YES;//为了使present的VC和当前VC在同一层级
[self.navigationController presentViewController:test animated:NO completion:^{
[test show:self.smallView];
}];
接下来就进入查看器页面,我们所用的拖动手势不是添加UIPinchGestureRecognizer拖拽手势
我们来使用toch event回调来实现拖拽动画
首先我们在- (void)touchesBegan里面判断是否拖拽的是我们想要拖拽的视图
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
CGPoint current = [touch locationInView:self.view];
CALayer *touchedLayer = [self.view.layer hitTest:current];
if(touchedLayer == self.smallView.layer){//判断拖拽的是否是我们要拖拽的视图
self.isMoving = YES;
}
}
接下来开始使用touchesMoved回调实现拖拽动画
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesMoved:touches withEvent:event];
if(!self.isMoving){//不是拖拽的相应视图不做任何操作
return;
}
UITouch *touch = [touches anyObject];
CGPoint current = [touch locationInView:self.view];//记录当前位置
CGPoint previous = [touch previousLocationInView:self.view];//记录手指之前位置
CGPoint center = self.smallView.center;
CGPoint offset = CGPointMake(current.x - previous.x, current.y - previous.y);
float height = current.y - self.view.nim_centerY;//记录距离原来视图的高度
if (offset.y <= 0){//是否向下拖拽
if (!_isBegin){//是否是刚开始拖动
self.smallView.center = CGPointMake(center.x + offset.x, center.y + offset.y);
if (height > 0){
self.smallView.nim_size = CGSizeMake(_smallView.nim_width * (self.view.nim_height - height)/_smallView.nim_height, self.view.nim_height - height);//拖拽后视图大小
self.bgView.alpha = (MaxHeight - height) / MaxHeight;//黑色背景透明度
}
}
}else{
_isBegin = false;
if (height > 0){
self.smallView.nim_size = CGSizeMake(_smallView.nim_width * (self.view.nim_height - height)/_smallView.nim_height, self.view.nim_height - height);
self.bgView.alpha = (MaxHeight - height) / MaxHeight;
}
self.smallView.center = CGPointMake(center.x + offset.x, center.y + offset.y);//设置视图位置
}
}
拖拽结束后,拖拽的高度大于一定的高度,关闭控制器
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesEnded:touches withEvent:event];
UITouch *touch = [touches anyObject];
CGPoint current = [touch locationInView:self.view];
float height = current.y - self.view.nim_centerY;
if (height > 50){//拖拽高度大于50关闭控制器
[self dismiss];
}else{//如果没有,回到原来的位置和大小
[UIView animateWithDuration:0.2 animations:^{
self.smallView.frame = self.view.bounds;
}];
}
self.isMoving = NO;
_isBegin = true;
}
以上就是拖拽动画,具体的实现方式可以查看demo