抽屉效果是移动应用最常用的效果之一,网易新闻、91手机助手都用到了这样效果,但实现的方法和细节上还有差别的。
先总结一下91助手般的抽屉效果
通过图片可以看到,抽屉效果的左右部分,左边是主功能的VIew,右边是与用户相关的View
那么要实现的功能点有:
一、点击让功能View右上角按纽后,用户功能菜单从右往左推出
二、当两个VIew同时出现时,点击主VIew右上角按纽或主View的视图时,收起抽屉
知道以上两点,就能知道具体的实现了。
首先创建主视图,并为主视图设置title,右边按纽
// 创建主视图
UIView *leftMainView = [[UIView alloc] initWithFrame:self.view.frame];
leftMainView.backgroundColor = [UIColor redColor];
// 为主视图绑定单击事件
UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lessPress:)];
[leftMainView addGestureRecognizer:tapRec];
// 创建一个UINavigationBar,并为其设置title,右边按纽
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"抽屉Demo"];
item.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"开关" style:UIBarButtonItemStyleDone target:self action:@selector(rightPress:)];
[navBar pushNavigationItem:item animated:YES];
[leftMainView addSubview:navBar];
// 创建右边用户菜单视图
UIView *rightSettingView = [[UIView alloc] initWithFrame:CGRectMake(leftMainView.frame.size.width, 0, 200, self.view.frame.size.height)];
rightSettingView.backgroundColor = [UIColor blueColor];
主要的两个视图创建好了,在创建一个UIScrollVIew,并将两个主视图设置到UIScrollView中
scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
scrollView.contentSize = CGSizeMake(leftMainView.frame.size.width + rightSettingView.frame.size.width, self.view.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.bounces = NO;
scrollView.scrollEnabled = NO;
[scrollView addSubview:leftMainView];
[scrollView addSubview:rightSettingView];
[self.view addSubview:scrollView];
UIScrollView的详细设置在
http://blog.youkuaiyun.com/amy2013113/article/details/8659059
1、点击右边按纽时打开抽屉
- (void) rightPress: (id)sender
{
// 获得UIScrollView当前的位置
float offSetX = scrollView.contentOffset.x;
if (offSetX == 0) {
// 如果offSetX等于0时,打开抽屉
[UIView animateWithDuration:0.6f animations:^{
scrollView.contentOffset = CGPointMake(200, 0);
}];
} else {
// 反之关闭抽屉
[UIView animateWithDuration:0.6f animations:^{
scrollView.contentOffset = CGPointMake(0, 0);
}];
}
}
2、如果抽屉的状态为已打开,点击主视图任意位置关闭抽屉
- (void) lessPress: (id)sender
{
float offSetX = scrollView.contentOffset.x;
if (offSetX == 200) {
[UIView animateWithDuration:0.6f animations:^{
scrollView.contentOffset = CGPointMake(0, 0);
}];
}
}
Demo下载
(本博文为博主原创,如需转载,请注明原文作者及文章来源。)