自己写的简单抽屉效果,大概原理都是一样的,直接放代码。
#import"DrawViewController.h"
@interfaceDrawViewController()
@property(nonatomic,weak)UIView*leftV;
@property(nonatomic,weak)UIView*rightV;
@property(nonatomic,weak)UIView*mainV;
@end
@implementationDrawViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view.
[selfsetup];
//添加拖动手势
UIPanGestureRecognizer*pan = [[UIPanGestureRecognizeralloc]initWithTarget:selfaction:@selector(pan:)];
[self.mainVaddGestureRecognizer:pan];
//给控制器添加点按手势
UITapGestureRecognizer*tap = [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(tap)];
[self.viewaddGestureRecognizer:tap];
}
- (void)tap{
//让mainv复位
[UIViewanimateWithDuration:0.5animations:^{
self.mainV.frame=self.view.bounds;
}];
}
#define R275
#define L -275
- (void)pan:(UIPanGestureRecognizer*)pan{
//获取偏移量
CGPointtransp = [pantranslationInView:self.mainV];
//self.mainV.transform = CGAffineTransformTranslate(self.mainV.transform, transp.x, 0);
self.mainV.frame= [selfframeWithOffset:transp.x];
//判断拖动方向
if(self.mainV.frame.origin.x>0){
//右
self.rightV.hidden=YES;
}elseif(self.mainV.frame.origin.x<0){
//左
self.rightV.hidden=NO;
}
//手指松开,自动定位
CGFloattarget =0;
if(pan.state==UIGestureRecognizerStateEnded) {
if(self.mainV.frame.origin.x> [UIScreenmainScreen].bounds.size.width*0.5) {
//右侧,大于屏幕一半
target =R;
}elseif(CGRectGetMaxX(self.mainV.frame) < [UIScreenmainScreen].bounds.size.width*0.5){
//左侧,最大x小于屏幕一半
target =L;
}
CGFloatoffset = target -self.mainV.frame.origin.x;
[UIViewanimateWithDuration:0.5animations:^{
self.mainV.frame= [selfframeWithOffset:offset];
}];
}
//复位
[pansetTranslation:CGPointZeroinView:self.mainV];
}
//固定向下偏移的最大距离
#define MAXY100
//根据偏移量计算mainV的frame
- (CGRect)frameWithOffset:(CGFloat)Offset{
CGRectframe =self.mainV.frame;
frame.origin.x+= Offset;
//向左移动时,y为负值,所以要取绝对值
frame.origin.y=fabs(frame.origin.x*MAXY/[UIScreenmainScreen].bounds.size.width);
//下方也要上移,所以mainV的高度要减去两倍
frame.size.height= [UIScreenmainScreen].bounds.size.height-2*frame.origin.y;
returnframe;
}
- (void)setup{
//左
UIView*leftV = [[UIViewalloc]initWithFrame:self.view.bounds];
leftV.backgroundColor= [UIColorblueColor];
self.leftV=leftV;
[self.viewaddSubview:leftV];
//右
UIView*rightV = [[UIViewalloc]initWithFrame:self.view.bounds];
rightV.backgroundColor= [UIColorgreenColor];
self.rightV=rightV;
[self.viewaddSubview:rightV];
//main
UIView*mainV = [[UIViewalloc]initWithFrame:self.view.bounds];
mainV.backgroundColor= [UIColorredColor];
self.mainV= mainV;
[self.viewaddSubview:mainV];
}
@end