iOS中倒計時

來源:互聯網
上載者:User

標籤:

方法一:使用NSTimer來實現(比較適用於傳送簡訊驗證碼倒計時)

主要是利用NSTimer的scheduledTimerWithTimeInterval方法來每秒執行一次changeTime方法

//建立一個Timer,每秒執行一次changeTime:方法

NSTimer * timer =[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTime:) userInfo:nil repeats:YES];

//changeTime

-(void)changeTime:(NSTimer*)timer

{

//點擊擷取驗證碼的btn

    UIButton * button = (UIButton*)[self.view viewWithTag:99];

    if (count == 0) {

//完成後invalidate掉

        [timer invalidate];

//59s倒計時

        count = 59;

        

        [button setTitle:@"重新擷取" forState:UIControlStateNormal];

        button.userInteractionEnabled = YES;

        button.alpha = 1;

    }

    else{

            [button setTitle:[NSString stringWithFormat:@"%d s",count] forState:UIControlStateNormal];

            count--;

    }

}

 

方法二:使用 GCD 來實現(比較使用於商家做某種活動的倒計時)

.h檔案中定義一個Timer來控制時間

//倒計時Timer

    dispatch_source_t _timer;

 

.m檔案中實現:

//建立一個時間戳記

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];

  //時間戳記的格式

        [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];

  //將相同時間戳記格式的NSString類型的資料轉換成NSDate類型的資料

        NSDate *endDate = [dateFormatter dateFromString:_EndTime];

        NSDate *startDate = [dateFormatter dateFromString:_StartTime];

        NSDate *currentDate = [dateFormatter dateFromString:_CurrentTime];

  //計算服務器目前時間距離活動結束的時間戳記

        NSTimeInterval timeInterval =[endDate timeIntervalSinceDate:currentDate];

  //計算服務器目前時間與活動開始時間的時間戳記

        NSTimeInterval StartToNow = [currentDate timeIntervalSinceDate:startDate];

  //倒計時時間

        __block int timeout = timeInterval;

        __block int StartTimeout = StartToNow;

        

        if (timeout!=0) {

            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// 並行隊列

// 並行隊列可以同時處理多個任務,在不得以的情況下可以用dispatch_queue_create建立,但一般我們都要用系統預定義的並行隊列,即全域隊列(Global // Concurrent Dispatch Queues)。目前系統預定義了四個不同運行優先順序的全域隊列,我們可以通過dispatch_get_global_queue來擷取它們。

//dispatch_get_global_queue第一個參數是隊列的優先順序,分別對應四個全域隊列:

//DISPATCH_QUEUE_PRIORITY_HIGH

//DISPATCH_QUEUE_PRIORITY_DEFAULT

//DISPATCH_QUEUE_PRIORITY_LOW

//DISPATCH_QUEUE_PRIORITY_BACKGROUND

 

//dispatch_get_global_queue中第二個參數目前系統保留,請設定為0即可。

 

  //每秒執行

            _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); 

            dispatch_source_set_event_handler(_timer, ^{

  //倒計時結束,關閉

                if(timeout<=0 || StartTimeout <=0){

                    dispatch_source_cancel(_timer);

                    _timer = nil;

 

//在隊列中運行任務

//你可以隨時向一個隊列中添加一個新任務,只需要調用一下dispatch_async即可:

                    dispatch_async(dispatch_get_main_queue(), ^{

  //可以根據自己需求設計需要顯示的內容及展現格式、風格等

                        dayLabel.text = @"0天";

                        hourLabel.text = @"00 :";

                        minLabel.text = @"00 :";

                        secLabel.text = @"00";

                        label.text = @"搶購結束!!!";

                    });

                }else{

                     label.text = @"搶購剩餘時間:";

                    int days = (int)(timeout/(3600*24));

                    if (days==0) {

                        dayLabel.text = @"";

                    }

                    int hours = (int)((timeout-days*24*3600)/3600);

                    int minute = (int)(timeout-days*24*3600-hours*3600)/60;

                    int second = timeout-days*24*3600-hours*3600-minute*60;

                    dispatch_async(dispatch_get_main_queue(), ^{

                        if (days==0) {

                            dayLabel.text = @"0天";

                        }else{

                            dayLabel.text = [NSString stringWithFormat:@"%d天",days];

                        }

                        if (hours<10) {

                            hourLabel.text = [NSString stringWithFormat:@"0%d :",hours];

                        }else{

                            hourLabel.text = [NSString stringWithFormat:@"%d :",hours];

                        }

                        if (minute<10) {

                            minLabel.text = [NSString stringWithFormat:@"0%d :",minute];

                        }else{

                            minLabel.text = [NSString stringWithFormat:@"%d :",minute];

                        }

                        if (second<10) {

                            secLabel.text = [NSString stringWithFormat:@"0%d",second];

                        }else{

                            secLabel.text = [NSString stringWithFormat:@"%d",second];

                        }

                        

                    });

                    timeout--;

                }

            });

            dispatch_resume(_timer);

        }

 

iOS中倒計時

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.