转载程序员iOS Developer

一行代码设置UINavigationBar渐变进度条

2016-12-26  本文已影响105人  一块豆腐

self.navigationController.navigationBar.sb_progress = 0.8;

GitHub地址

类似于QQ加载网页时候在UINavigationBar上的进度条

要实现一行代码实现渐变进度条需要以下操作

//1.导入UINavigationBar+Item 
//2.在UINavigationController 中实现下面两个方法
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item
{
    navigationBar.sb_gradientProgress.hidden = YES;
    return YES;
}

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
    navigationBar.sb_gradientProgress.hidden = YES;
    return YES;
}
//3.设置进度
self.navigationController.navigationBar.sb_progress = 0.8;

SBGradientProgress 是一个带有渐变动画的View,主要思路是给gradientlayer设置渐变颜色,做key为“colors”的动画

- (void)startAnimation
{
    //设置初始渐变值
    [self gradientColors];
    
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"colors"];
    anim.values = [self animValues];
    [anim setDuration:1];
    [anim setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    anim.repeatCount = MAXFLOAT;
    [self.layer addAnimation:anim forKey:nil];
}


/**
 纯色进度条
 */
- (void)setPureColor:(UIColor *)pureColor
{
    _pureColor = pureColor;
    if (pureColor == nil) {
        
        [self startAnimation];
    } else {
        CAGradientLayer *layer = (id)[self layer];
        layer.colors = @[(id)pureColor.CGColor,(id)pureColor.CGColor];
        [self.layer removeAllAnimations];
    }
}


/**
 乾坤大挪移(最后一个放到前面)
 */
- (NSArray *)shiftColors:(NSArray *)colors {
    
    NSMutableArray *mutable = [colors mutableCopy];
    id last = [mutable lastObject];
    [mutable removeLastObject];
    [mutable insertObject:last atIndex:0];
    
    return [NSArray arrayWithArray:mutable];
}



/**
 动画的values <NSArray *<color>>
 */
- (NSArray *)animValues
{
    CAGradientLayer *layer = (id)[self layer];
    NSMutableArray *values = [NSMutableArray array];
    NSArray *colors = nil;
    for (NSInteger deg = 0; deg <= 360; deg += 5) {
        if (values.count) {
            colors = values[deg / 5 - 1];
        } else {
            colors = layer.colors;
        }
        [values addObject:[self shiftColors:colors]];
    }
    
    return values;
}

<img src="http:https://img.haomeiwen.com/i1899979/42a50711400da6a6.gif?imageMogr2/auto-orient/strip" width = "300" height = "500" alt="好像有点大" align=center />

参考项目,思路类似,但做动画的原理不一样

最后祝你们早日脱离苦海

上一篇下一篇

猜你喜欢

热点阅读