抽屉效果
实现:
1.界面切换
2.界面复位
3.界面自动转换
- (void)viewDidLoad {
[super viewDidLoad];
[self setViewUp];
//添加手势
UIPanGestureRecognizer *panGs = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGs:)];
[self.redView addGestureRecognizer:panGs];
//添加监听手势复位
[self addTapGesture];
}
//添加手势
- (void)addTapGesture{
UITapGestureRecognizer *tapGs = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
[self.view addGestureRecognizer:tapGs];
}
- (void)tapAction{
[UIView animateWithDuration:0.7 animations:^{
self.redView.frame = [[UIScreen mainScreen] bounds];
}];
}
#define targetR 350
#define targetL -350
#define middleX [UIScreen mainScreen].bounds.size.width*0.5
- (void)panGs:(UIPanGestureRecognizer *)panGs {
CGPoint point = [panGs translationInView:self.redView];
if(self.redView.frame.origin.x >0){
self.greenView.hidden = YES;
}else{
self.greenView.hidden = NO;
}
self.redView.frame = [self frameWithPointX:point.x];
//自动复位
if(panGs.state == UIGestureRecognizerStateEnded){
CGFloat target = 0;
if(self.redView.frame.origin.x > middleX){
target = targetR;
}else if (CGRectGetMaxX(self.redView.frame)<middleX){
target = targetL;
}
[UIView animateWithDuration:0.4 animations:^{
CGFloat offset = target - self.redView.frame.origin.x;
self.redView.frame = [self frameWithPointX:offset];
}];
}
[panGs setTranslation:CGPointZero inView:self.redView];
}
#define screenW [UIScreen mainScreen].bounds.size.width
#define screenFrame [UIScreen mainScreen].bounds
- (CGRect)frameWithPointX:(CGFloat)offsetX {
CGRect frame = self.redView.frame;
frame.origin.x += offsetX;
CGFloat translationY = fabs(frame.origin.x* 100 / screenW);
frame.origin.y =translationY;
frame.size.height = [UIScreen mainScreen].bounds.size.height - 2*frame.origin.y;
return frame;
}
- (void)setViewUp{
//redView;
UIView *redView = [[UIView alloc] initWithFrame:screenFrame];
redView.backgroundColor = [UIColor redColor];
self.redView = redView;
//blueView
UIView *blueView = [[UIView alloc] initWithFrame:screenFrame];
blueView.backgroundColor = [UIColor blueColor];
self.blueView = blueView;
//greenView
UIView *greenView = [[UIView alloc] initWithFrame:screenFrame];
greenView.backgroundColor = [UIColor greenColor];
self.greenView = greenView;
//添加view
[self.view addSubview:blueView];
[self.view addSubview:greenView];
[self.view addSubview:redView];
}
效果图