基本信息
文件名称:iOS实现简易的抽屉效果.docx
文件大小:16.63 KB
总页数:4 页
更新时间:2025-07-01
总字数:约2.7千字
文档摘要

iOS实现简易的抽屉效果

本文实例为大家分享了iOS实现简易的抽屉效果的具体代码,供大家参考,具体内容如下

1.添加需要实现抽屉效果的三个视图,这里需要注意主视图需要放在最后添加

//左边视图

//右边视图

?...

//主视图

??UIView*mainView=[[UIViewalloc]initWithFrame:self.view.bounds];

??mainView.backgroundColor=[UIColorgreenColor];

??_mainView=mainView;

??[self.viewaddSubview:mainView];

2.实现左滑显示左边视图,右滑出现右边视图

添加平移手势和点击手势,实现左右滑动的监听和点击复位的效果

//添加平移手势

??UIPanGestureRecognizer*panGes=[[UIPanGestureRecognizeralloc]initWithTarget:selfaction:@selector(panGes:)];

??[self.mainViewaddGestureRecognizer:panGes];

??//添加点击返回手势

??UITapGestureRecognizer*tapGes=[[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(tap)];

??[self.viewaddGestureRecognizer:tapGes];

在平移手势调用的方法中,通过偏移量来确定mainView的frame,实现动画效果

首先通过translationInView:方法获取偏移量,通过偏移量的正负确定拖动的方向当手指松开后需要根据mainView的x值确定其视图是定位到原始位置还是其缩放的位置要其视图由当前点位移到目标位置,可以通过当前点到目标点的位移,然后调用frameWithOffsetX:方法获得mainView的frame

#definetargetR300

#definetargetL-300

-(void)panGes:(UIPanGestureRecognizer*)panGes

??//获取偏移量

??CGPointtranP=[panGestranslationInView:self.mainView];

??//获得位移后的视图

??self.mainView.frame=[selfframeWithOffsetX:tranP.x];

??//判断拖动方向

??if(self.mainView.frame.origin.x0){//向左

????self.rightView.hidden=NO;

??}elseif(self.mainView.frame.origin.x0)

??{//向右

????self.rightView.hidden=YES;

??}

??//当手指松开时,做自动定位

??CGFloattarget=0;

??if(panGes.state==UIGestureRecognizerStateEnded){

????if(self.mainView.frame.origin.x0.5*screenW){

??????target=targetR;

????}elseif(CGRectGetMaxX(self.mainView.frame)0.5*screenW)

????{

??????target=targetL;

????}

????//offset为当前点到其目标点的位移

????CGFloatoffset=target-self.mainView.frame.origin.x;

????[UIViewanimateWithDuration:0.5animations:^{

??????self.mainView.frame=[selfframeWithOffsetX:offset];

????}];

??}

??//复位

??[panGessetTranslation:CGPointZeroinView:self.mainView];

}

#definemaxY120

//根据mainView在X轴方向位移确定mainView的尺寸

-(CGRect)