首页 > 代码库 > iOS学习 - 22 全局跑马灯

iOS学习 - 22 全局跑马灯

思路:

1.创建一个单例

+ (instancetype)shareManager {
    static CCPaomaView *pModel = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        pModel = [[CCPaomaView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.0468 *KScreenHeight)];
    });
    return pModel;
}

2.把接收的数据存在本地的 plist,不适用于大量数据,每次读取第一个数据,读取完成删除整个 plist,再把剩下的重新存进 plist

3.根据动画代理,监听动画执行结束,将动画实例置为 nil

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    NSLog(@"%@",[self.paomaLabel.layer animationForKey:@"paoMaDeng"]);
    if ([self.paomaLabel.layer animationForKey:@"paoMaDeng"] == anim) {
        //移除第一组数据
        [_array removeObjectAtIndex:0];
        
        //移除整个 plist
        [CCPaomaModel removePaomaPlist];
        
        //重新写入
        [_array writeToFile:[CCPaomaModel filename] atomically:YES];
        
        //动画停止之后,将实例置为 nil
        _pmAniamtion = nil;
        
        //数组为空之后移除跑马灯
        if (_array.count > 0) {
            [self showPaomaView:self.superview];
        }else{
            self.hidden = YES;
            [self removeFromSuperview];
        }
        NSLog(@"%@",self.array);
    }
}

4.判断动画实例是否为空,使得切换界面,跑马灯继续,而不是重新开始

- (void)paomaAniamtion:(CGFloat)count{
    //判断动画实例存不存在,存在继续,不存在即创建
    if (_pmAniamtion == nil) {
        _pmAniamtion = [CABasicAnimation animation];
        _pmAniamtion.keyPath = @"transform.translation.x";
        CGFloat W = CGRectGetWidth(_paomaLabel.bounds);
        _pmAniamtion.fromValue = @(W);
        _pmAniamtion.toValue = @(-W);
        _pmAniamtion.duration = _aniTime;
        _pmAniamtion.repeatCount = count;
        _pmAniamtion.removedOnCompletion = NO;       //动画结束不移除
        _pmAniamtion.fillMode = kCAFillModeForwards; //动画结束会保持结束的状态
        _pmAniamtion.delegate = self;                //设置代理
        [_paomaLabel.layer addAnimation:_pmAniamtion forKey:@"paoMaDeng"];
    }else{
        _pmAniamtion.repeatCount = count;
    }
}

5.切换界面,暂停、恢复动画

#pragma mark -- 界面出现、消失,创建、恢复、暂停动画
- (void)viewWillAppear:(BOOL)animated {
    [_paomaView showPaomaView:self.view];
    [_paomaView resumeAnimation];
}

- (void)viewWillDisappear:(BOOL)animated {
    [_paomaView pauseAniamtion];
}

话不多说,github 见代码

 

iOS学习 - 22 全局跑马灯