ios ~ 上下翻页(轮播图,广告),计时器NSTimer的"启动"与"停止"、"暂停"和"继续"

原理:NSTimer+UICollectionView
-- 动态图.gif -- -- 静态图 --
RPReplay_Final1660207053.GIF
IMG_0136.jpg
1:首先熟悉一下NSTimer的常用属性
-(void)fire // 启动
- (void)invalidate; // 停止

这个是唯一一个可以将计时器从runloop中移出的方法。

2:NSTimer为了取消内存以及和循环引用的问题 ,在NSTimer停止的时候(invalidate)要做的处理
[_timerinvalidate];// 停止  从Runlop中移除

_timer = nil;      // 放在内存溢出,重置为nil

3、计时器NSTimer"启动""停止""暂停""继续"

暂停和继续:NSTimer有一个属性:@property (copy) NSDate *fireDate;,使用set方法,[self.timer setFireDate:(NSDate * _Nonnull)];

Timer启动:

_timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(updateStepWithCusInterval) userInfo:nil repeats:YES];

Timer停止:

[self.timer invalidate];

但是注意:invalidate方法会完全释放了Timer对象,是无法从暂停中再恢复定时,只能重新生成Timer对象,再开启定时。

怎么可以暂停定时器,用NSDatedistantFutre方法
[self.timer setFireDate:[NSDate distantFutre]]; //  NSTimer暂停

需要继续的时候调用date方法

[self.timer setFireDate:[NSDate date]]; //  NSTimer继续

4、下面是例子:一个简单的天气预警Demo

if (self.weatherWarningModels.count > 0) {
        
    self.earlyWarningView.hidden = NO;
    self.earlyWarningView.weatherWarningModels = self.weatherWarningModels;
    [self.earlyWarningView refreshView];
    // 点击,进入天气 预警或异常 详情页:
    self.earlyWarningView.clickWarnIngModelBlock = ^(GWHome_WeatherWarningAndAbnormalModel * _Nonnull weatherWarningAndAbnormalModel) {
        [LCM_AlertViewFactory showToastWithMessage:weatherWarningAndAbnormalModel.title];
            
    };
        
} else {
    self.earlyWarningView.hidden = YES;
}

.h

#import <UIKit/UIKit.h>
#import "GWHome_WeatherWarningAndAbnormalModel.h" // 【首页】:天气预警 + 异常天气

NS_ASSUME_NONNULL_BEGIN

@interface CWEarlyWarning_WeatherImgView : UIView

// 预警天气 + 异常天气
@property (nonatomic, strong) NSArray<GWHome_WeatherWarningAndAbnormalModel *> *weatherWarningModels;

/** 点击,直接返回该点击预警或天气异常的model */
@property (nonatomic, copy) void (^clickWarnIngModelBlock) (GWHome_WeatherWarningAndAbnormalModel *weatherWarningAndAbnormalModel);


- (void)refreshView;

@end

NS_ASSUME_NONNULL_END

.m

//  预警 ,比如: 大雨红色预警(上下翻页)

#import "CWEarlyWarning_WeatherImgView.h"
#import "CWEarlyWarning_WeatherImgViewCell.h"

@interface CWEarlyWarning_WeatherImgView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) NSInteger itemCell; // cell的索引值
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation CWEarlyWarning_WeatherImgView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = RGBA(181, 66, 62, 1);
        [self setupUI];
    }
    return self;
}


- (void)refreshView {
    
    if (self.weatherWarningModels.count > 1) {
        
        NSMutableArray *alertArr = [NSMutableArray arrayWithCapacity:0];
        alertArr = [self.weatherWarningModels mutableCopy];
        
        [alertArr addObject:self.weatherWarningModels[0]]; // 将第一个元素,取出在放到可变数组中,排在末尾啊
        self.weatherWarningModels = [alertArr copy];
        
        [self.collectionView reloadData]; // 在循环之前,刷新(更新)一下,将最新的数组数据赋值上。

        if (_timer) {
            [_timer invalidate];
            _timer = nil;
        }
         
        self.itemCell = 0;
        [self.collectionView setContentOffset:CGPointMake(0,0)animated:NO];
        // [self startIconRunLoop]; // 加上这行会闪退
        _timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(startIconRunLoop) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        [_timer fire]; // 立即 启动
        
    } else {
        if (_timer) {
            [_timer invalidate]; // 停止,从Runlop中移除
            _timer = nil; // 放在内存溢出,重置为nil
        }
    }
    
    [self.collectionView reloadData];
}

- (void)startIconRunLoop {
    
    self.itemCell = self.itemCell + 1;
    
    if (self.itemCell <= self.weatherWarningModels.count) {
        
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.itemCell-1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionCenteredVertically) animated:YES];
    } else {

        [self.collectionView setContentOffset:CGPointMake(0,0)animated:NO];
        self.itemCell = 1;
        
        [self startIconRunLoop];
    }
}

- (void)dealloc {
    [_timer invalidate]; // 停止,从Runlop中移除
    _timer = nil; // 放在内存溢出,重置为nil
}


- (void)setupUI {
    
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _layout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width/375*118, [UIScreen mainScreen].bounds.size.width/375*22);
    _layout.minimumLineSpacing = 10;
    _layout.minimumInteritemSpacing = 0;
    _layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _collectionView= [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/375*118, [UIScreen mainScreen].bounds.size.width/375*22) collectionViewLayout:self.layout];
    
//    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.scrollEnabled = NO;
    [self addSubview:self.collectionView];
    [self.collectionView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    [self.collectionView registerClass:[CWEarlyWarning_WeatherImgViewCell class] forCellWithReuseIdentifier:NSStringFromClass([CWEarlyWarning_WeatherImgViewCell class])];
    
}

#pragma mark -- -- < UICollectionViewDelegate, UICollectionViewDataSource >
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.weatherWarningModels.count;
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CWEarlyWarning_WeatherImgViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([CWEarlyWarning_WeatherImgViewCell class]) forIndexPath:indexPath];

    if (self.weatherWarningModels.count) {
        GWHome_WeatherWarningAndAbnormalModel *model = self.weatherWarningModels[indexPath.row];
        
        // 等级: 0金色(异常天气),预警: 1红色,2橙色 ,3 黄色,4 蓝色
        if (model.level == 0) {
            [cell.warningBut setBackgroundImage:[UIImage imageNamed:@"weather_abNormal_bg_icon"] forState:UIControlStateNormal];
        } else if (model.level == 1) {
            [cell.warningBut setBackgroundImage:[UIImage imageNamed:@"weather_warning_Red_icon"] forState:UIControlStateNormal];
        } else if (model.level == 2) {
            [cell.warningBut setBackgroundImage:[UIImage imageNamed:@"weather_warning_Orange_icon"] forState:UIControlStateNormal];
        } else if (model.level == 3) {
            [cell.warningBut setBackgroundImage:[UIImage imageNamed:@"weather_warning_Yellow_icon"] forState:UIControlStateNormal];
        } else if (model.level == 4) {
            [cell.warningBut setBackgroundImage:[UIImage imageNamed:@"weather_warning_Blue_icon"] forState:UIControlStateNormal];
        }
        [cell.warningBut setTitle:[NSString stringWithFormat:@"%@ ", model.title] forState:UIControlStateNormal];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.clickWarnIngModelBlock) {
        self.clickWarnIngModelBlock(self.weatherWarningModels[indexPath.row]);
    }
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容