IOS development diary 46-Implementation of Countdown effect, ios diary 46-countdown
Today, the blogger needs to implement the countdown effect and has encountered some difficulties. I would like to share with you the hope that we can make common progress.
First, analyze the total countdown time where necessary. The bloggers are not encapsulated. You can encapsulate them by yourself.
# Pragma mark -------- new modification and increased countdown
NSString * stringOfTime = [NSString stringWithFormat: @ "% @", d [@ "shipping_time"];
Double endUnixTime = [stringOfTime doubleValue];
// NSLog (@ "++ %. 2f", endUnixTime );
NSCalendar * cal = [NSCalendar currentCalendar];
Unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate * date1 = [NSDate date];
NSDate * date2 = [NSDate dateWithTimeIntervalSince1970: endUnixTime];
NSDateComponents * dOfd = [cal components: unitFlags fromDate: date1 toDate: date2 options: 0];
NSInteger sec = [dOfd hour] * 3600 + [dOfd minute] * 60 + [dOfd second];
// Sec is the total number of minutes
// NSLog (@ "************ % @", dOfd );
UILabel * labelOfTime = (UILabel *) [_ scroll viewWithTag: 6954321];
If (sec> 0 ){
[Self setCountDownWithTotalSec: sec withLabel: labelOfTime];
}
Then use GCD to implement the countdown Function
-(Void) setCountDownWithTotalSec :( NSInteger) totalSec withLabel :( UILabel *) timeLbl {
_ Block NSInteger timeout = totalSec; // countdown time
Dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 );
Dispatch_source_t _ 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); // execution per second
Dispatch_source_set_event_handler (_ timer, ^ {
If (timeout <= 0) {// countdown ends, close
Dispatch_source_cancel (_ timer );
Dispatch_async (dispatch_get_main_queue (), ^ {
// Set the button on the settings page as needed
TimeLbl. text = @ "00:00:00 ";
});
} Else {
Long hours = timeout/3600;
Long minutes = (timeout-hours * 3600)/60;
Int seconds = timeout % 60;
NSString * strTime = [NSString stringWithFormat: @ "%. 2ld %. 2ld %. 2d", hours, minutes, seconds];
NSString * Firth = [strTime substringWithRange: NSMakeRange (0, 1)];
NSString * secondH = [strTime substringWithRange: NSMakeRange (1, 1)];
NSString * firstM = [strTime substringWithRange: NSMakeRange (2, 1)];
NSString * secondM = [strTime substringWithRange: NSMakeRange (3, 1)];
NSString * firstS = [strTime substringWithRange: NSMakeRange (4, 1)];
NSString * secondS = [strTime substringWithRange: NSMakeRange (5, 1)];
NSString * newTimeString = [NSString stringWithFormat: @ "% @%@:%%@:%%%@", Firth, secondH, firstM, secondM, firstS, secondS];
Dispatch_async (dispatch_get_main_queue (), ^ {
TimeLbl. text = newTimeString; // return to the main thread
});
Timeout --;
}
});
Dispatch_resume (_ timer );
}