#import "SSYViewController.h"
#define ScreenW [UIScreen mainScreen].bounds.size.width
#define ScreenH [UIScreen mainScreen].bounds.size.height
#define targetR 275
#define targetL -275
@interface SSYViewController ()
@property (nonatomic ,weak) UIView *leftView;
@property (nonatomic ,weak) UIView *rightView;
@property (nonatomic ,weak) UIView *midView;
@end
@implementation SSYViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setUp];
[self addpan];
}
//添加手势
-(void)addpan{
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self.midView addGestureRecognizer:pan];
}
//监听者调用手势执行的方法
-(void)pan:(UIPanGestureRecognizer *)pan{
CGPoint transP = [pan translationInView:self.midView];
self.midView.frame = [self framWithOffsetX:transP.x];
if(pan.state == UIGestureRecognizerStateEnded){
//自动定位
CGFloat target = 0;
//1.当mainV的x大于屏幕宽度一半时,自动定位到右侧
if (self.midView.frame.origin.x > ScreenW * 0.5) {
//自动定位到右侧
target = targetR;
}else if(CGRectGetMaxX(self.midView.frame) < ScreenW * 0.5){
//2.当mainV的最大的X值,小于屏幕,宽度一半时,自动定位到左侧
target = targetL;
}
CGFloat offsetX = target - self.midView.frame.origin.x;
[UIView animateWithDuration:0.5 animations:^{
self.midView.frame = [self framWithOffsetX:offsetX];
}];
}
[pan setTranslation:CGPointZero inView:self.midView];
}
//计算移动后的尺寸
-(CGRect)framWithOffsetX:(CGFloat)offsetX{
CGRect frame = self.midView.frame;
frame.origin.x += offsetX;
frame.origin.y = fabs(frame.origin.x * 100 /[UIScreen mainScreen].bounds.size.width);
frame.size.height = [UIScreen mainScreen].bounds.size.height - 2*frame.origin.y;
self.midView.frame = frame;
if (self.midView.frame.origin.x > 0) {
self.rightView.hidden = YES;
}else if(self.midView.frame.origin.x < 0){
self.rightView.hidden = NO;
}
return frame;
}
//设置界面
-(void)setUp{
//添加左边的view
UIView *leftView = [[UIView alloc] initWithFrame:self.view.bounds];
leftView.backgroundColor = [UIColor redColor];
self.leftView = leftView;
[self.view addSubview:leftView];
//添加右边的view
UIView *rightView = [[UIView alloc] initWithFrame:self.view.bounds];
rightView.backgroundColor = [UIColor blueColor];
self.rightView = rightView;
[self.view addSubview:rightView];
//添加中间的view
UIView *midView = [[UIView alloc] initWithFrame:self.view.bounds];
midView.backgroundColor = [UIColor purpleColor];
self.midView = midView;
[self.view addSubview:midView];
}
@end