iOS实现滑动弧形菜单的思路与方法

时间:2021-05-02

前言

最近公司的项目中需要用到弧形菜单,起初自定义uicollectionview的layout,但实现出的效果并不符合项目中要求按钮始终垂直于界面、界面始终保持几个按钮等一系列需求(是我水平不够),后来索性用uiview写了一个弧形可滑动菜单。

效果如下:

实现思路:

1、根据思路可以自己确定到半径与圆心的每个按钮所在的x点,可根据数学公式求得y点

2、给按钮添加拖动手势uipangesturerecognizer,根据偏移量x计算出对应偏移弧线的距离,根据圆的运动轨迹赋值给按钮的x 并更新 y

3、结束拖动手势的时候计算偏移距离、根据是否划到下一个按钮的一半的width来实施动画更新按钮的center

实现细节:

已知圆心、半径与x值求y值:(x-a)^2 + (y - b)^ 2 = r2。

用到的uipangesturerecognizer的三种状态:uigesturerecognizerstatebegan\uigesturerecognizerstatechanged\uigesturerecognizerstateended

用uipangesturerecognizer的locationinview方法来确定当前点的位置

? 1 2 3 4 5 6 7 8 9 10 11 if(pgr.state==uigesturerecognizerstatebegan){ self.endmove = no; self.beginpoint=[pgr locationinview:self]; }else if (pgr.state==uigesturerecognizerstatechanged){ self.movepoint= [pgr locationinview:self]; self.movex = sqrt(fabs(self.movepoint.x - self.beginpoint.x) * fabs(self.movepoint.x - self.beginpoint.x) + fabs(self.movepoint.y - self.beginpoint.y) * fabs(self.movepoint.y - self.beginpoint.y)); }

计算出偏移的x点后要根据起始点来判断用户是向左滑动还是向右滑动

? 1 2 3 4 5 if (self.movepoint.x>self.beginpoint.x) { self.movenum += self.movex; } else{ self.movenum -= self.movex; }

之后判断判断是否超过了所有按钮所在的范围并赋值

? 1 2 3 4 5 6 7 if (self.movenum > 0) { self.movenum = 0; } if (self.movenum < -((screen_width - 20 - subvieww)/(self.showbtncount - 1)) * (self.subviewarray.count - self.showbtncount)) { self.movenum = -((screen_width - 20 - subvieww)/(self.showbtncount - 1)) * (self.subviewarray.count - self.showbtncount); }

将偏移量赋值给x并更新y值

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ///中心点 cgfloat yy = 0.0; cgfloat xx = 0.0; cgfloat margin = 0.0; ///子视图x中点 uiview *view = self.subviewarray[0]; cgfloat subcenterx = view.frame.size.width / 2; for (nsinteger i=0; i<self.subviewarray.count ;i++) {// 178,245 margin = i * ((screen_width - 20 - view.frame.size.width)/(self.showbtncount - 1)); xx = 10 + subcenterx + fabs(self.subviewx) + margin + self.movenum; yy = sqrt((self.radius - self.circlemargin / 2) * (self.radius - self.circlemargin / 2) - (xx - self.radius) * (xx - self.radius)) + self.radius; if (xx >= self.radius - (self.radius - self.circlemargin / 2) && xx <= self.radius + (self.radius - self.circlemargin / 2)) { uibutton *button=[self.subviewarray objectatindex:i]; nslog(@"~~~~~~~%@",button); if (self.isendmove) { [uiview animatewithduration:0.3 animations:^{ button.center=cgpointmake(xx , yy); }]; } else{ button.center=cgpointmake(xx , yy); } } nslog(@"xx:%f---------yy:%f",xx,yy); }

原理大概就是这些

然后把项目中的效果直接做了简单的封装传了个demo

github地址:https://github.com/xuuhan/hxcambermenu

总结

以上就是这篇文章的全部内容了,实现的效果和功能可能还有着明显的限制,希望同学们多多指教,同时也希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://www.jianshu.com/p/e66f2cd3db14

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章