倒計時是乙個常用的功能頁面, 該功能可以分解成3步: ①倒計時ui的展示 ②定時資料的格式與解析 ③定時器的選擇
下面通過3個知識點來完成整個功能
1. uidatepicker
uidatepicker 是乙個系統封裝好控制器類,封裝了 uipickerview,但是他是uicontrol的子類,專門用於接受日期、時間和持續時長的輸入,我們對於時間選擇的ui可以直接使用該類去完成,下面貼出具體使用**
@property (nonatomic, strong) uidatepicker *datepicker; //設定為屬性
- (void)configpickerview __tvos_prohibited;
對應樣式如下
1.1 uidatepickermodetime
uidatepickermodetime
1.2 uidatepickermodedate
uidatepickermodedate
1.3 uidatepickermodedateandtime
uidatepickermodedateandtime
1.4 uidatepickermodecountdowntimer
uidatepickermodecountdowntimer
2. cron表示式
cron表示式就是對時間資料的一種處理,可以和後台商量好都使用這個方式去解析時間資料,舉個例子:8 27 22 1 3 ? 2019,代表時間2023年3月1日22點27點8秒,具體**如下
獲取當前時間值(秒為單位)
nsdate* nowdate = [nsdate date];
nstimezone* zone = [nstimezone timezonewithname:@"asia/shanghai"];
nstimeinterval time = [zone secondsfromgmtfordate:nowdate];// 以秒為單位返回當前時間與系統格林尼治時間的差
int newtime = ([nowdate timeintervalsince1970]+time);
int nowhour = newtime / 3600;
int nowminite = newtime / 60 % 60;
int newsecond = newtime % 60;
nowhour %= 24;
newtime = 3600*nowhour+60*nowminite+newsecond;
在將newtime傳入下面引數,即可獲得當前時間的cron表示式
+(nsstring*)cronstringwithtime:(long long)time
week:(nsinteger)week
weekday:(nsinteger)weekday
nsstring* cron;
long hour = time / 3600;
long min = time / 60 % 60;
long second = time % 60;
//執行一次 應該設定 日月年, tbd.
nsstring* weekdesp=@"";
if(week == 0)else if(week == 127)elseelseelse{
int hour = timeout / 3600;
int minute = timeout / 60 % 60;
int second = timeout % 60;
dispatch_async(dispatch_get_main_queue(), ^{
//設定介面的按鈕顯示 根據自己需求設定
self.timerlabel.text = [nsstring stringwithformat:@"%02d:%02d:%02d",hour,minute,second];
timeout -= 1;
dispatch_resume(self.timer);
定時器肯定需要注意釋放問題,需要在專案中合適的時機釋放該定時器
#pragma mark 生命週期
dispatch_source_cancel(_timer); //關閉定時器
- (void)dealloc
nslog(@"釋放了我就放心了!!!"); //可以在dealloc看一下有沒有log的列印
iOS 倒計時按鈕
1 新建乙個類,取名為 timerbtn,繼承uibutton 2 在timer.h中新增如下 import inte ce timerbtn uibutton 建立倒計時按鈕 param frame 位置大小 param title 標題 param ntimer 倒計時時間 return 倒計時...
iOS倒計時動畫
效果圖 製作成gif之後,幀率變快了,看起來很彆扭,實際上是每秒執行一次的 h 檔案 inte ce countdownview uiview property nonatomic,assign long long time property nonatomic,assign,readonly lo...
ios開發實現倒計時功能
對於有支付功能的ios軟體,訂單一般都會有乙個訂單的時間,過了這個時間後訂單自動取消,因此要實現倒計時功能。首先獲得剩餘時間的時間戳 毫秒數 lefttime nsstring lefttimeinteger lefttime integervalue 定義乙個計時器 timer nstimer s...