仿keep長按按鈕的實現(xiàn)

需求來源

最近看到keep跑步結(jié)束按鈕,長按效果還是挺不錯的,正好和我們的業(yè)務(wù)邏輯一致,就仿照keep的效果,實現(xiàn)了一個長按按鈕。具體的思路和核心代碼如下:

實現(xiàn)思路

查看keep的效果后,發(fā)現(xiàn)是在長按按鈕之后,將控件放大一定的倍數(shù),然后按照控件原來的大小,繪制一個圓,等到圓形繪制完成之后,長按結(jié)束,進行相應(yīng)的業(yè)務(wù)邏輯的操作??傮w的思路大概是這樣,接下來就是具體的實現(xiàn)代碼了。

實現(xiàn)代碼

創(chuàng)建一個按鈕,并添加長按手勢
//結(jié)束按鈕
@property (nonatomic, strong) UIButton *endBtn;
[self addSubview:self.endBtn];
[self.endBtn mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(self).offset(0);
        make.width.height.equalTo(@(Width_Real(60)));
        make.top.equalTo(self).offset(topHeight);
    }];
- (UIButton *)endBtn
{
    if (!_endBtn) {
        _endBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_endBtn setImage:[UIImage imageNamed:@"icon_new_endBtn"] forState:(UIControlStateNormal)];
        _endBtn.hidden = NO;
        UILongPressGestureRecognizer *longPG=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPG:)];
        longPG.minimumPressDuration = 0.1;
        [_endBtn addGestureRecognizer:longPG];
    }
    return _endBtn;
}
繪制圓的代碼,這個代碼相對比較簡單,這里就不再贅述了,直接貼代碼了
#define degreesToRadians(x) (M_PI*(x)/180.0) //把角度轉(zhuǎn)換成PI的方式
@property (nonatomic, weak) CAShapeLayer *progressLayer;
@property (nonatomic,weak)  UIBezierPath *path;
@property (nonatomic,weak) CAShapeLayer *trackLayer;

- (void)drawRect:(CGRect)rect {
    
    CGFloat topHeight = 0.0;
    if ([SGMJCommonTool judgeIsSafeAres]) {
       
        topHeight = Width_Real(53) + Width_Real(40);
    }
    else
    {
        topHeight = Width_Real(35);
    }
    
    // 創(chuàng)建一個tracker(軌道layer)圓環(huán)內(nèi)部
    CAShapeLayer *trackLayer = [CAShapeLayer layer];
    trackLayer.frame = rect;
    [self.layer addSublayer:trackLayer];
    trackLayer.fillColor =[[UIColor blackColor] colorWithAlphaComponent:0.5].CGColor;
    trackLayer.strokeColor = [UIColor whiteColor].CGColor;
    self.trackLayer=trackLayer;
    // 背景透明度
    trackLayer.opacity = 0.6f;
    trackLayer.lineCap = kCALineCapRound;
    trackLayer.lineWidth = Width_Real(3);
    // 創(chuàng)建軌道
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(rect.size.width / 2, topHeight + Width_Real(60)/2) radius:Width_Real(60)/2 - Width_Real(3) / 2 startAngle:degreesToRadians(-90) endAngle:degreesToRadians(270) clockwise:YES];
    //    trackLayer.path = [path CGPath];
    self.path=path;
    path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(rect.size.width / 2, topHeight + Width_Real(60)/2) radius:Width_Real(60)/2 - Width_Real(3) / 2 startAngle:degreesToRadians(Width_Real(3) / 2 - 90) endAngle:degreesToRadians(270 - Width_Real(3) / 2) clockwise:YES];
    CAShapeLayer *progressLayer = [CAShapeLayer layer];
    progressLayer.frame = rect;
    progressLayer.fillColor = [UIColor clearColor].CGColor;
    progressLayer.strokeColor = [UIColor redColor].CGColor;
    progressLayer.lineCap = kCALineCapRound;
    progressLayer.lineWidth = Width_Real(3);
    progressLayer.path = [path CGPath];
    progressLayer.strokeEnd = 0.00f;
    self.progressLayer = progressLayer;
    
    CALayer *gradientLayer = [CALayer layer];
    CAGradientLayer *gradientLayer1 = [CAGradientLayer layer];
    gradientLayer1.frame = CGRectMake(0, 0, rect.size.width , rect.size.height);
    [gradientLayer1 setColors:[NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor],(id)[[UIColor whiteColor] CGColor],(id)[[UIColor whiteColor] CGColor], nil]];
    [gradientLayer1 setStartPoint:CGPointMake(0.5, 0)];
    [gradientLayer1 setEndPoint:CGPointMake(0.5, 1)];
    [gradientLayer addSublayer:gradientLayer1];
    
    
    // progressLayer來截取漸變層, fill是clear stroke有顏色
    [gradientLayer setMask:progressLayer];
    [self.layer addSublayer:gradientLayer];
}
處理手勢回調(diào),在開始長按時,將按鈕的大小變?yōu)橹暗?.2倍,并開啟一個定時器,因為需求要求的是在2秒內(nèi)進度達到百分之百,所以每隔0.02秒調(diào)用下繪制的方法,在長按按鈕結(jié)束時,判斷進度是否達到100,并將控件大小恢復(fù)原樣,具體代碼如下:
@property (nonatomic , strong)NSTimer *timer;

@property (nonatomic, assign) CGFloat currentProgress;

@property (nonatomic, assign) NSInteger index;

//長按按鈕回調(diào)方法
-(void)longPG:(UILongPressGestureRecognizer *)pg{
    
    switch (pg.state) {
        case UIGestureRecognizerStateBegan:{
            
            [UIView animateWithDuration:0.1
                             animations:^{
                self.endBtn.transform = CGAffineTransformMakeScale(1.2, 1.2);
            }completion:^(BOOL finish){
                
            }];
            self.index = 1;
            self.currentProgress = 1;
            self.timer = [NSTimer timerWithTimeInterval:0.02 target:self selector:@selector(timerEvent) userInfo:nil
                                                repeats:YES];
            [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
            
            break;
        }
            
        case UIGestureRecognizerStateEnded:{
            
            if (self.currentProgress >= 100) {
                
                //處理長按結(jié)束業(yè)務(wù)邏輯
            }
            
            //清除定時器
            if (self.timer) {
                
                [self.timer invalidate];
                self.timer = nil;
            }
            
            [UIView animateWithDuration:0.1
                             animations:^{
                self.endBtn.transform = CGAffineTransformMakeScale(1.0, 1.0);
            }completion:^(BOOL finish){

            }];
           
            [self setPercet:00 withTimer:0.1];
            
            break;
        }
            
           
        case UIGestureRecognizerStateChanged:
        {
            
        }
        default:
            break;
    }
}

- (void)timerEvent {
    self.index+=1;
    [self setPercet:self.index withTimer:0.02];
    if (self.index >=100) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)setPercet:(CGFloat)percent withTimer:(CGFloat)time {
    [CATransaction begin];
    [CATransaction setDisableActions:NO];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
    [CATransaction setAnimationDuration:time];
    _progressLayer.strokeStart=0.00f;
    _progressLayer.strokeEnd = percent / 100.0f;
    _currentProgress = percent;
    [CATransaction commit];
}

結(jié)尾

到這里,長按按鈕的邏輯已經(jīng)實現(xiàn)了,當然在操作的時候,也可以去添加一些交互,比如在短按按鈕時,提示用戶需要長按按鈕才可以等。具體的代碼就不在這里贅述了,如果有什么問題,歡迎在評論區(qū)留言。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容