#import "ViewController.h"
#import "redView.h"
@interface ViewController ()// 控制器.m文件
@property(nonatomic, weak) UIView *blueV;
@property(nonatomic, weak) redView *redV;
@property(nonatomic, weak) UIView *greenV;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化
[self setUP];
}
// 初始化
- (void)setUP
{
// 添加3个不同的View
UIView *blueView = [[UIView alloc] init];
UIView *greenView = [[UIView alloc] init];
redView *redV = [[redView alloc] init];
self.blueV = blueView;
self.redV = redV;
self.greenV = greenView;
self.redV.greenV = greenView;
// 设置3个界面的背景颜色和frame
blueView.backgroundColor = [UIColor blueColor];
redV.backgroundColor = [UIColor redColor];
greenView.backgroundColor = [UIColor greenColor];
blueView.frame = self.view.bounds;
greenView.frame = self.view.bounds;
redV.frame = self.view.bounds;
// 添加视图
[self.view addSubview:blueView];
[self.view addSubview:greenView];
[self.view addSubview:redV];
}
@end
// redView.h文件
#import <UIKit/UIKit.h>
@interface redView : UIView
@property(nonatomic ,weak) UIView *greenV;
@end
// redView.m文件
#import "redView.h"
@implementation redView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
// 创建一个拖动手势
UIPanGestureRecognizer *panPG = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panPg:)];
// 添加手势
[self addGestureRecognizer:panPG];
}
return self;
}
// 当用户手指拖动当前view时调用
- (void)panPg:(UIPanGestureRecognizer *)panPG
{
// 拿到偏移量的点
CGPoint transP = [panPG translationInView:self];
if (self.frame.origin.x > 0)
{
self.greenV.hidden = YES;
}else
{
self.greenV.hidden = NO;
}
self.transform = CGAffineTransformTranslate(self.transform, transP.x, 0);
CGFloat X = self.frame.origin.x;
X += transP.x;
CGFloat Y = fabs(X/[UIScreen mainScreen].bounds.size.width * 30);
CGFloat W = [UIScreen mainScreen].bounds.size.width;
CGFloat y = fabs(X/[UIScreen mainScreen].bounds.size.width * 30);
CGFloat H = [UIScreen mainScreen].bounds.size.height - 2 * y;
self.frame = CGRectMake(X, Y, W, H);
// 复位
[panPG setTranslation:CGPointZero inView:self];
// 判断各种情况定位
[UIView animateWithDuration:0.2 animations:^{
// 当停止手势时调用
if (panPG.state == UIGestureRecognizerStateEnded) {
if (self.frame.origin.x > [UIScreen mainScreen].bounds.size.width * 0.5)
{
[self changeFrame:275];
}else if(CGRectGetMaxX(self.frame) < [UIScreen mainScreen].bounds.size.width * 0.5)
{
[self changeFrame:-275];
}else
{
self.frame = [UIScreen mainScreen].bounds;
}
}
}];
}
// 定位当前控件的frame
- (void)changeFrame:(CGFloat)x
{
CGRect frame = self.frame;
frame.origin.x = x;
frame.origin.y = 30;
frame.size.height = [UIScreen mainScreen].bounds.size.height - 60;
self.frame = frame;
}
@end