标签:
#define screenW [UIScreen mainScreen].bounds.size.width
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong)UIView * redView;
@property (nonatomic,strong)UIView *yellowView;
@property (nonatomic,strong)UIView *greenView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setUpView];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
[self.view addGestureRecognizer:pan];
}
//根据当前最前面视图的frame确定是否隐藏第二个View
- (void)Hidden{
if (self.greenView.frame.origin.x>0) {//往右移动,显示黄色的View
self.yellowView.hidden = NO;
}else if (self.greenView.frame.origin.x<0){//往左移动,隐藏黄色的View
self.yellowView.hidden = YES;
}
}
#define rightLocation 275
#define leftLocation -250
#pragma mark pan的方法
- (void)pan:(UIPanGestureRecognizer *)pan{
//获取手势移动的位置
CGPoint point = [pan translationInView:self.view];
//获取X轴的偏移量
CGFloat offSetX = point.x;
//修改greenView的frame
self.greenView.frame = [self changeFrameWith:offSetX];
//判断greenViewdex是否大于0
[self Hidden];
//复位
[pan setTranslation:CGPointZero inView:self.view];
//判断下当手势结束的时候,定位
if (pan.state == UIGestureRecognizerStateEnded) {
CGFloat target = 0;
if (self.greenView.frame.origin.x > screenW * 0.5) {
target = rightLocation;
}else if (CGRectGetMaxX(self.greenView.frame)<screenW * 0.5){
target = leftLocation;
}
//获取偏移量
CGFloat offSetX = target-self.greenView.frame.origin.x;
[UIView animateWithDuration:0.25 animations:^{
self.greenView.frame = target == 0?self.view.bounds:[self changeFrameWith:offSetX];
}];
}
}
#define MaxY 100
//根据偏移量获取一个新的frame
#pragma mark - 根据offSetX计算greenView的frame
- (CGRect)changeFrameWith:(CGFloat)offSetX{
//获取上一次的frame
CGRect frame = self.greenView.frame;
//获取上一次的高和宽
CGFloat oldW = frame.size.width;
CGFloat oldH = frame.size.height;
//移动后的x
CGFloat curX =frame.origin.x + offSetX;
//y轴方向偏移量
CGFloat offsetY = offSetX*MaxY/screenW;
//当前的frame高度
CGFloat curH = frame.size.height - 2*offsetY;
if (frame.origin.x<0) {//往左移动
curH = oldH+2*offsetY;
}
//获取尺寸的缩放比例
CGFloat scale = curH/oldH;
CGFloat curW = oldW * scale;
CGFloat curY = (self.view.frame.size.height - curH)*0.5;
//更改frame
frame.origin.x = curX;
frame.origin.y = curY;
frame.size.width = curW;
frame.size.height = curH;
return frame;
}
#pragma mark 添加View
- (void)setUpView{
self.redView = [[UIView alloc]initWithFrame:self.view.frame];
self.redView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.redView];
self.yellowView = [[UIView alloc]initWithFrame:self.view.frame];
self.yellowView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:self.yellowView];
self.greenView = [[UIView alloc]initWithFrame:self.view.frame];
self.greenView.backgroundColor = [UIColor greenColor];
[self.view addSubview:self.greenView];
}
@end
标签:
原文地址:http://www.cnblogs.com/zmloveworld/p/5166634.html