最常见的向右滑动显示菜单栏,其实就是两个或多个图层等级不一的视图。向右滑动时,最上面的图层根据滑动幅度来改变Frame(相对于父类复层)x值。现在常见的例如QQ侧滑显示菜单栏:下面的图层Frame.X值起初不是为0的,当顶级图层Frame.X的值为0时,监测滑动幅度是否大于0(作者取值为80),通过滑动幅度改变上下图层Frame.X的值。
废话不多说了,上代码吧:
//添加手势
UIPanGestureRecognizer*panGesture = [[UIPanGestureRecognizer alloc] initWithTarget: self action: @selector(changeFrame:)];
[self.view addGestureRecognizer: panGesture];
#pragma侧滑显示菜单
-(void)changeFrame:(UIPanGestureRecognizer*)recognizer{
//获取滑动幅度
CGPointtranslation = [recognizertranslationInView:self.view];//在某个view上面滑动幅度
float x = translation.x;//纪录滑动幅度
NSLog(@"%f",x);
[UIViewanimateWithDuration:0.5delay:0options:UIViewAnimationOptionCurveEaseOutanimations:^{
if(x >=0) {//实现跟手势改变位置
_contentView.frame=CGRectMake(x,0,SCREEN_WIDTH,SCREEN_HEIGHT);
_personMenuView.view.frame=CGRectMake(-SCREEN_WIDTH/3*2+ (x *0.9),0,SCREEN_WIDTH,SCREEN_HEIGHT);
}
}completion:nil];
if(recognizer.state==UIGestureRecognizerStateEnded) {
//当手势完成时,看最终幅度是否大于你预设的值,大于设置动画(展示菜单),小于时回到原处(隐藏菜单图层)
[UIViewanimateWithDuration:0.5delay:0options:UIViewAnimationOptionCurveEaseOutanimations:^{
if(x >80) {
_contentView.frame=CGRectMake(SCREEN_WIDTH/5*4+10,0,SCREEN_WIDTH,SCREEN_HEIGHT);
_personMenuView.view.frame=CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
}else{
_contentView.frame=CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
_personMenuView.view.frame=CGRectMake(-SCREEN_WIDTH/3*2,0,SCREEN_WIDTH,SCREEN_HEIGHT);
}
}completion:nil];
}
}
}
我写的虽然很简单,但是句句属实,比起网络上面的繁琐好多了