Use GCD for countdown, and gcd for countdown

Source: Internet
Author: User

Use GCD for countdown, and gcd for countdown

The effect is as follows:

ViewController. h

1 #import <UIKit/UIKit.h>2 3 @interface ViewController : UIViewController4 @property (assign, nonatomic) NSInteger surplusSecond;5 6 @property (strong, nonatomic) IBOutlet UILabel *lblMessage;7 @property (strong, nonatomic) IBOutlet UIButton *btnSendCAPTCHA;8 9 @end

ViewController. m

1 # import "ViewController. h "2 3 @ interface ViewController () 4-(void) layoutUI; 5-(void) countDown; 6 @ end 7 8 @ implementation ViewController 9 # define kSurplusSecond 510 11-(void) viewDidLoad {12 [super viewDidLoad]; 13 14 [self layoutUI]; 15} 16 17-(void) didReceiveMemoryWarning {18 [super didReceiveMemoryWarning]; 19 // Dispose of any resources that can be recreated.20} 21 22-(void) layoutUI {23 _ surplusSecond = kSurplusSecond; // the remaining number of seconds. This indicates the number of seconds after the verification code is sent. You can click the "verify" button again to send the verification code 24 25_btnsendcaptcha. tintColor = [UIColor darkGrayColor]; 26 _ btnSendCAPTCHA. layer. masksToBounds = YES; 27 _ btnSendCAPTCHA. layer. cornerRadius = 10.0; 28 _ btnSendCAPTCHA. layer. borderColor = [UIColor grayColor]. CGColor; 29 _ btnSendCAPTCHA. layer. borderWidth = 1.0; 30} 31 32/** 33 * countDown 34 */35-(void) countDown {36 // global concurrency queue 37 di Spatch_queue_t globalQueue = dispatch_get_global_queue (queue, 0); 38 // main queue column; belonging to serial queue 39 dispatch_queue_t mainQueue = dispatch_get_main_queue (); 40 41 // scheduled cyclic execution event 42 // The dispatch_source_set_timer method is worth mentioning as the last parameter (leeway), which tells the system the accuracy of timer triggering. All timers do not guarantee 100% accuracy. this parameter is used to tell the system how much effort you want the system to ensure accuracy. If you want a timer to be triggered every five seconds, and the more accurate the better, you can pass 0 as the parameter. In addition, if it is a periodic task, such as checking email, you will want to check every 10 minutes, but not so precise. Therefore, you can pass in 60 to tell the system that the 60-second error is acceptable. Its significance is to reduce resource consumption. 43 kernel timer = dispatch_source_create (kernel, 0, 0, globalQueue); 44 kernel (timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC); 45 kernel (timer, ^ {// timer Event processor 46 NSLog (@ "Event Handler"); 47 if (_ surplusSecond <= 0) {48 dispatch_source_cancel (timer); // cancel the timer cycle timer; so that the handle is called, that is, the event is executed 49 dispatch_async (mainQueue, ^ {50 _ btnSendCAPTCHA. enabled = YES; 51 [_ btnSendCAPTCHA setTitle: @ "verify" forState: UIControlStateNormal]; 52 53 _ lblMessage. text = @ "using GCD for countdown effect"; 54 _ surplusSecond = kSurplusSecond; 55}); 56} else {57 _ surplusSecond --; 58 dispatch_async (mainQueue, ^ {59 NSString * btnInfo = [NSString stringWithFormat: @ "% ld second", (long) (_ surplusSecond + 1)]; 60 _ btnSendCAPTCHA. enabled = NO; 61 [_ btnSendCAPTCHA setTitle: btnInfo forState: UIControlStateDisabled]; 62}); 63} 64}); 65 dispatch_source_set_cancel_handler (timer, ^ {// timer cancels the processor; execute 66 NSLog (@ "Cancel Handler"); 67}); 68 dispatch_resume (timer) when calling dispatch_source_cancel; // restore the timer of the regular cycle; after the Dispatch Source is created, its status is suspended by default and needs to be automatically restored. Otherwise, the event will not be passed or executed 69} 70 71-(IBAction) sendCAPTCHA :( id) sender {72 _ lblMessage. text = [NSString stringWithFormat: @ "Verification Code sent successfully. You can resend it in % d seconds.", kSurplusSecond]; 73 74 [self countDown]; 75} 76 77 @ end

Main. storyboard

 

1 <? Xml version = "1.0" encoding = "UTF-8" standalone = "no"?> 2 <document type = "com. apple. interfaceBuilder3.CocoaTouch. storyboard. XIB "version =" 3.0 "toolsVersion =" 7706 "systemVersion =" 14E46 "targetRuntime =" iOS. cocoaTouch "propertyAccessControl =" none "useAutolayout =" YES "useTraitCollections =" YES "initialViewController =" vXZ-lx-hvc "> 3 <dependencies> 4 <deployment identifier =" iOS "/> 5 <plugIn identifier = "com. apple. interfaceBuilder. IBCocoaTouchPlugin "version =" 7 703 "/> 6 </dependencies> 7 <scenes> 8 <! -- View Controller --> 9 <scene sceneID = "ufC-wZ-h7g"> 10 <objects> 11 <viewController id = "vXZ-lx-hvc" customClass = "ViewController" sceneMemberID = "viewController"> 12 <layoutGuides> 13 <viewControllerLayoutGuide type = "top" id = "jyV-Pf-zRb"/> 14 <viewControllerLayoutGuide type = "bottom" id = "2fi-mo-0CV"/> 15 </layoutGuides> 16 <view key = "view" contentMode = "scaleToFill" id = "kh9-bI-dsS"> 17 <rect key = "frame" x = "0.0" y = "0.0 "width =" 600 "height =" 600 "/> 18 <autoresizingMask key =" autoresizingMask "flexibleMaxX =" YES "flexibleMaxY =" YES "/> 19 <subviews> 20 <label opaque = "NO" userInteractionEnabled = "NO" contentMode = "left" leading = "251" leading = "251" text = "use GCD for countdown" lineBreakMode = "tailTruncation" baselineAdjustment = "alignBaselines" adjustsFontSizeToFit = "NO" leading = "NO" id = "1Kh-pV-cfz"> 21 <rect key = "frame" x = "200" y = "289.5" width = ""200" height = "20.5"/> 22 <fontDescription key = "fontDescription" type = "system" pointSize = "17"/> 23 <color key = "textColor" cocoaTouchSystemColor = "darkTextColor"/> 24 <nil key = "highlightedColor"/> 25 </label> 26 <button opaque = "NO" contentMode = "scaleToFill" placement = "center" contentVerticalAlignment = "center" buttonType = "roundedRect" lineBreakMode = "middleTruncation" placement = "NO" id = "rFe-Xb-ZSc"> 27 <rect key = "frame" x = "240 "y =" 510 "width =" 120 "height =" 50 "/> 28 <constraints> 29 <constraint firstAttribute =" width "constant =" 120 "id =" gVH- aT-gen "/> 30 <constraint firstAttribute =" height "constant =" 50 "id =" jJP-Vc-fpy "/> 31 </constraints> 32 <state key = "normal" title = "Verification"> 33 <color key = "titleShadowColor" white = "0.5" alpha = "1" colorSpace = "calibratedWhite"/> 34 </state> 35 <connections> 36 <action selector = "sendCAPTCHA: "destination =" vXZ-lx-hvc "eventType =" touchUpInside "id =" I6T-s9-9H6 "/> 37 </connections> 38 </button> 39 </subviews> 40 <color key = "backgroundColor" white = "1" alpha = "1" colorSpace = "custom" customColorSpace = "calibratedWhite"/> 41 <constraints> 42 <constraint firstattriitem = "centerX" secondItem = "rFe-Xb-ZSc" secondAttribute = "centerX" id = "CoE-CP-eDN"/> 43 <constraint firstAttribute = "centerY" secondItem = "1Kh-pV-cfz" secondAttribute =" centerY "id =" bX4-jS-0xm "/> 44 <constraint firstAttribute =" centerX "secondItem =" 1Kh-pV-cfz "secondAttribute =" centerX "id =" mKH-Zw-Utb "/> 45 <constraint firstItem = "2fi-mo-0CV" firstAttribute = "top" secondItem = "rFe-Xb-ZSc" secondAttribute = "bottom" constant = "40" id = "y3Q-IA-qIO"/> 46 </ constraints> 47 </view> 48 <connections> 49 <outlet property = "btnSendCAPTCHA" destination = "rFe-Xb-ZSc" id = "UFG-TS-ImX"/> 50 <outlet property = "lblMessage" destination = "1Kh-pV-cfz" id = "gzx-3T-euc"/> 51 </connections> 52 </viewController> 53 <placeholder placeholderIdentifier = "IBFirstResponder" id =" x5A-6p-PRh "sceneMemberID =" firstResponder "/> 54 </objects> 55 </scene> 56 </scenes> 57 </document>

Output result:

1 2015-08-31 14:40:02.083 KMCountDown[5102:103949] Event Handler2 2015-08-31 14:40:03.087 KMCountDown[5102:103949] Event Handler3 2015-08-31 14:40:04.084 KMCountDown[5102:103949] Event Handler4 2015-08-31 14:40:05.086 KMCountDown[5102:103971] Event Handler5 2015-08-31 14:40:06.085 KMCountDown[5102:103949] Event Handler6 2015-08-31 14:40:07.085 KMCountDown[5102:103949] Event Handler7 2015-08-31 14:40:07.085 KMCountDown[5102:103949] Cancel Handler

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.