本文实例为大家分享了iOS实现简易的抽屉效果的具体代码,供大家参考,具体内容如下 1.添加需要实现抽屉效果的三个视图,这里需要注意主视图需要放在最后添加 // 左边视图 ... /
本文实例为大家分享了iOS实现简易的抽屉效果的具体代码,供大家参考,具体内容如下
1.添加需要实现抽屉效果的三个视图,这里需要注意主视图需要放在最后添加
// 左边视图
...
// 右边视图
...
// 主视图
UIView *mainView=[[UIView alloc]initWithFrame:self.view.bounds];
mainView.backgroundColor=[UIColor greenColor];
_mainView=mainView;
[self.view addSubview:mainView];
2.实现左滑显示左边视图,右滑出现右边视图
添加平移手势和点击手势,实现左右滑动的监听和点击复位的效果
// 添加平移手势
UIPanGestureRecognizer *panGes=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGes:)];
[self.mainView addGestureRecognizer:panGes];
// 添加点击返回手势
UITapGestureRecognizer *tapGes=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
[self.view addGestureRecognizer:tapGes];
在平移手势调用的方法中,通过偏移量来确定mainView的frame,实现动画效果
translationInView:
方法获取偏移量,通过偏移量的正负确定拖动的方向frameWithOffsetX:
方法获得mainView的frame#define targetR 300
#define targetL -300
- (void)panGes:(UIPanGestureRecognizer *)panGes
{
// 获取偏移量
CGPoint tranP=[panGes translationInView:self.mainView];
// 获得位移后的视图
self.mainView.frame=[self frameWithOffsetX:tranP.x];
// 判断拖动方向
if (self.mainView.frame.origin.x<0) {//向左
self.rightView.hidden=NO;
}else if(self.mainView.frame.origin.x>0)
{// 向右
self.rightView.hidden=YES;
}
// 当手指松开时,做自动定位
CGFloat target=0;
if (panGes.state==UIGestureRecognizerStateEnded) {
if (self.mainView.frame.origin.x>0.5*screenW) {
target=targetR;
}else if(CGRectGetMaxX(self.mainView.frame)<0.5*screenW)
{
target=targetL;
}
//offset为当前点到其目标点的位移
CGFloat offset=target-self.mainView.frame.origin.x;
[UIView animateWithDuration:0.5 animations:^{
self.mainView.frame=[self frameWithOffsetX:offset];
}];
}
// 复位
[panGes setTranslation:CGPointZero inView:self.mainView];
}
#define maxY 120
// 根据mainView在X轴方向位移确定mainView的尺寸
- (CGRect)frameWithOffsetX:(CGFloat)offsetX
{
CGRect frame=self.mainView.frame;
frame.origin.x+=offsetX;
frame.origin.y=fabs(frame.origin.x / screenW * maxY);
frame.size.height=screenH - frame.origin.y * 2;
return frame;
}
3.如何让其他文件也能实现抽屉效果
@interface ViewController :AZDrawerController
// 当一个控制器的View添加到另一个控制器的View上的时候,那此时View所在的控制器也应该成为上一个控制器的子控制器.
AZTableViewController *vc1=[[AZTableViewController alloc]init];
vc1.view.frame=self.mainView.bounds;
[self.mainView addSubview:vc1.view];
[self addChildViewController:vc1];
--结束END--
本文标题: iOS实现简易的抽屉效果
本文链接: https://www.lsjlt.com/news/172054.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0