#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, weak) UIView *mainV;
@property (nonatomic, weak) UIView *leftV;
@property (nonatomic, weak) UIView *rightV;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 添加子控件
[self setUpChildView];
// 添加Pan手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self.view addGestureRecognizer:pan];
// 利用KVO时刻监听mainV的frame属性
// Observer:观察者 谁想监听
// KeyPath:监听的属性
// options:监听新值的改变
[_mainV addObserver:self forKeyPath:keyPath(_mainV, frame) options:NSKeyValueObservingOptionNew context:nil];
}
// 只要监听的属性一改变,就会调用观察者的这个方法,通知你有新值
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%@",NSStringFromCGRect(_mainV.frame));
if (_mainV.frame.origin.x > 0) { // 往右边移动,隐藏蓝色的view
_rightV.hidden = YES;
}else if (_mainV.frame.origin.x < 0){ // 往左边移动,显示蓝色的view
_rightV.hidden = NO;
}
}
// 在对象销毁的时候,一定要注意移除观察者
- (void)dealloc
{
// 移除观察者
[_mainV removeObserver:self forKeyPath:@"frame"];
}
#pragma mark - pan的方法
- (void)pan:(UIPanGestureRecognizer *)pan
{
// 获取手势的移动的位置
CGPoint transP = [pan translationInView:self.view];
// 获取X轴的偏移量
CGFloat offsetX = transP.x;
// 修改mainV的Frame
_mainV.frame = [self frameWithOffsetX:offsetX];
// 复位
[pan setTranslation:CGPointZero inView:self.view];
}
#pragma mark - 根据offsetX计算mainV的Frame
- (CGRect)frameWithOffsetX:(CGFloat)offsetX
{
CGRect frame = _mainV.frame;
frame.origin.x += offsetX;
return frame;
}
#pragma mark - 添加子控件
- (void)setUpChildView
{
// left
UIView *leftV = [[UIView alloc] initWithFrame:self.view.bounds];
leftV.backgroundColor = [UIColor greenColor];
[self.view addSubview:leftV];
_leftV = leftV;
// right
UIView *rightV = [[UIView alloc] initWithFrame:self.view.bounds];
rightV.backgroundColor = [UIColor blueColor];
[self.view addSubview:rightV];
_rightV = rightV;
// main
UIView *mainV = [[UIView alloc] initWithFrame:self.view.bounds];
mainV.backgroundColor = [UIColor redColor];
[self.view addSubview:mainV];
_mainV = mainV;
}