iOS建行转盘

2018-02-08 10:26:26来源:https://www.jianshu.com/p/b4f96159666b作者:iOS骆驼人点击

分享


导语:


之前公司在做一个应急的项目,需要是在首页做一个类似建行转盘手动滚动的视图,网上大部分都是安卓的demo,于是参考其思想写了一份iOS版的建行转盘效果。



1.实现思路

1.自定义一个UIView,view里添加button控件;
2.给父视图添加一个UIPanGestureRecognizer手势,根据手势的状态来获取用户的触摸位置和旋转弧度,刷新UI。




gif5新文件.gif
2.具体实现代码

给外界提供一个方法(需要子控件button对应的图片、文字以及中心图片)


#pragma mark - 转动手势
- (void)zhuanPgr:(UIPanGestureRecognizer *)pgr{
if(pgr.state==UIGestureRecognizerStateBegan) { //开始时重置mTmpAngle和触摸开始时间
mTmpAngle = 0;
beginPoint = [pgr locationInView:self];//第一触碰点
startTouchDate = [NSDate date];
} else if (pgr.state == UIGestureRecognizerStateChanged) { //获取触摸点所在的区间来计算旋转的角度和抬起时旋转的角度,不断去改变mStartAngle,更新UI
float StartAngleLast = mStartAngle;
movePoint= [pgr locationInView:self]; //第二触碰点
float start = [self getAngle:beginPoint]; //获得起始弧度
float end = [self getAngle:movePoint]; //结束弧度

if ([self getQuadrant:movePoint] == 1 || [self getQuadrant:movePoint] == 4) {
mStartAngle += end - start;
mTmpAngle += end - start;
} else { // 二、三象限,角度值是负值
mStartAngle += start - end;
mTmpAngle += start - end;
}
[self layoutBtn];

beginPoint = movePoint;
speed = mStartAngle - StartAngleLast;
} else if (pgr.state==UIGestureRecognizerStateEnded) { // 计算每秒移动的角度,如果达到mFlingableValue的大小,则认为需要自动滚动
NSTimeInterval time= [[NSDate date] timeIntervalSinceDate:startTouchDate];
anglePerSecond = mTmpAngle*50/ time;

if (fabsf(anglePerSecond) > mFlingableValue && !_isPlaying) {
_isPlaying = YES;
flowtime = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(autoflow) userInfo:nil repeats:YES];
}
}
}
//根据触摸的位置,计算角度
- (float)getAngle:(CGPoint)point {
double x = point.x - mRadius;
double y = point.y - mRadius;
return (float) (asin(y / hypot(x, y)));
}
/**
* 根据当前位置计算象限
*
* @return point
*/
- (int)getQuadrant:(CGPoint) point {
int tmpX = (int) (point.x - mRadius);
int tmpY = (int) (point.y - mRadius);
if (tmpX >= 0) {
return tmpY >= 0 ? 1 : 4;
} else {
return tmpY >= 0 ? 2 : 3;
}
}
///自动滚动
- (void) autoflow {
if ( fabs(speed) < 0.001 ) {//如果速度小于一定的值则结束滚动,关闭定时器
_isPlaying = false;
[flowtime invalidate];
flowtime = nil;
return;
}

// 不断改变mStartAngle,更新UI
mStartAngle += speed ;
speed = speed/1.05;
[self layoutBtn];
}
///更新子控件UI
- (void)layoutBtn {
for (NSInteger i = 0; i<_numOfSubView ;i++) {
CGFloat centerY= _frame.size.height/2 + sin((i/_numOfSubView)*M_PI*2+mStartAngle) * (self.frame.size.width/2 - _subViewSize.width/2 - margin);
CGFloat centerX=_frame.size.height/2 + cos((i/_numOfSubView)*M_PI*2+mStartAngle) * (self.frame.size.width/2 - _subViewSize.width/2 - margin);
UIButton *button=[btnArray objectAtIndex:i];
button.center=CGPointMake(centerX, centerY);
}
}

参考链接 Andorid建行转盘








最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台