1.效果图
,
2.storyboard 中设置
3.代码实现
#import "ZHDrawerVC.h"
@interface ZHDrawerVC ()
@property(weak,nonatomic)UIView *rightView; //黄色View
@property(weak,nonatomic)UIView *leftView; //蓝色View
@property(weak,nonatomic)UIView *mainView; //红色View
@end
@implementation ZHDrawerVC
- (void)viewDidLoad {
[super viewDidLoad];
[self setUp];
//给主View添加拖拽手势
UIPanGestureRecognizer *panP = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
[self.mainView addGestureRecognizer:panP];
//给控制器添加单击手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
[self.view addGestureRecognizer:tap];
}
//单击之后调用方法
-(void)tap{
[UIView animateWithDuration:0.5 animations:^{
self.mainView.frame = [UIScreen mainScreen].bounds;
}];
}
//拖拽手势方法
-(void)pan:(UIPanGestureRecognizer *)pan{
CGPoint transP = [pan translationInView:self.mainView];
// self.mainView.transform = CGAffineTransformMakeTranslation(transP.x,0);
// NSLog(@"%f",transP.x);
self.mainView.frame = [self frameWithOffset:transP.x];
if (self.mainView.frame.origin.x > 0) {
self.leftView.hidden = YES;
}if (self.mainView.frame.origin.x < 0) {
self.leftView.hidden = NO;
}
CGFloat target = 0;
if (pan.state == UIGestureRecognizerStateEnded) {
if (self.mainView.frame.origin.x > [UIScreen mainScreen].bounds.size.width * 0.5) {
target = 275;
}else if(CGRectGetMaxX(self.mainView.frame)<[UIScreen mainScreen].bounds.size.width*0.5){
target = -275;
}
CGFloat offset = target - self.mainView.frame.origin.x;
[UIView animateWithDuration:0.5 animations:^{
self.mainView.frame = [self frameWithOffset:offset];
}];
}
[pan setTranslation:CGPointZero inView:self.mainView];
}
//根据偏移量返回mainView当前的frame
-(CGRect)frameWithOffset:(CGFloat)offset{
CGRect frame = self.mainView.frame;
frame.origin.x = frame.origin.x + offset;
self.mainView.frame = frame;
CGFloat y = fabs(frame.origin.x * 100 /[UIScreen mainScreen].bounds.size.width);
frame.origin.y = y;
frame.size.height = [UIScreen mainScreen].bounds.size.height - 2 * y;
return frame;
}
//给控制器添加三个UIView
-(void)setUp{
UIView *rightView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
rightView.backgroundColor = [UIColor yellowColor];
self.rightView = rightView;
[self.view addSubview:rightView];
UIView *leftView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
leftView.backgroundColor = [UIColor blueColor];
self.leftView = leftView;
[self.view addSubview:leftView];
UIView *mainView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
mainView.backgroundColor = [UIColor redColor];
self.mainView = mainView;
[self.view addSubview:mainView];
}
@end