我们在用QQ时都会发现,消息列表向左滑动时,左侧的功能界面被显示出来,消息列表会拉到最右侧, 就像一个抽屉拉出来一样。除了QQ, 还有网易新闻等应用都采用了这样的交互。本文就以此介绍简易版的抽屉效果.
实现步骤
1.声明三个View属性
@interface ViewController ()
@property (nonatomic, strong) UIView *mainView;
@property (nonatomic, strong) UIView *leftView;
@property (nonatomic, strong) UIView *rightView;
@end
- (void)viewDidLoad {
[super viewDidLoad];
[self creatChildView];
[self addGesture];
// 通过KVO来监听mainView的frame的变化,从而判断maimView是左滑还是右滑。
[_mainView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
}
2.创建View
在这注意view的添加顺序, 我们想要让最初显示的view为mainView
- (void)creatChildView
{
self.leftView = [[UIView alloc] initWithFrame:self.view.bounds];
_leftView.backgroundColor = [UIColor greenColor];
[self.view addSubview:_leftView];
_rightView = [[UIView alloc] initWithFrame:self.view.bounds];
_rightView.backgroundColor = [UIColor blueColor];
[self.view addSubview:_rightView];
self.mainView = [[UIView alloc] initWithFrame:self.view.bounds];
_mainView.backgroundColor = [UIColor redColor];
[self.view addSubview:_mainView];
}
3.给self.view添加一个平移手势
- (void)addGesture
{
// 创建手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
[self.view addGestureRecognizer:pan];
}
4.手势触发方法
- (void)panAction:(UIPanGestureRecognizer *)panGesture
{
// 获取平移手势移动后, 在相对坐标中的偏移量
CGPoint point = [panGesture translationInView:self.view];
// 声明xNew变量用point.x赋值
CGFloat xNew = point.x;
// 改变mainView的frame
_mainView.frame = CGRectMake(xNew + self.mainView.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);
// 设置手势移动后的point
[panGesture setTranslation:CGPointZero inView:panGesture.view];
}
5.只要被监听的属性发生变化, 就会触发这个方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
// 如果往右侧移动, 显示左边,隐藏右边
if (_mainView.frame.origin.x > 0) {
_rightView.hidden = YES;
// 往左移动,显示右边
} else if (_mainView.frame.origin.x < 0) {
_rightView.hidden = NO;
}
}
效果如下图
这次实现的是简易版的抽屉效果, 仅仅是用了三个view, 但在开发中一般为几个不同的VC, 通过手势实现抽屉效果, 同时还能设置一些动画效果, 比如比较有名的MMDrawerController框架.要是项目有需要, 可以参考这个第三方. 如何实现几个控制器间的抽屉效果, 下次再与大家分享.