使用 GCD 实现倒计时效果

效果如下:

使用 GCD 实现倒计时效果

ViewController.h

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController
@property (assign, nonatomic) NSInteger surplusSecond; @property (strong, nonatomic) IBOutlet UILabel *lblMessage;
@property (strong, nonatomic) IBOutlet UIButton *btnSendCAPTCHA; @end

ViewController.m

 #import "ViewController.h"

 @interface ViewController ()
- (void)layoutUI;
- (void)countDown;
@end @implementation ViewController
#define kSurplusSecond 5 - (void)viewDidLoad {
[super viewDidLoad]; [self layoutUI];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (void)layoutUI {
_surplusSecond = kSurplusSecond; //剩余秒数;这里指验证码发送完,间隔多少秒才能再次点击「验证」按钮进行发送验证码 _btnSendCAPTCHA.tintColor = [UIColor darkGrayColor];
_btnSendCAPTCHA.layer.masksToBounds = YES;
_btnSendCAPTCHA.layer.cornerRadius = 10.0;
_btnSendCAPTCHA.layer.borderColor = [UIColor grayColor].CGColor;
_btnSendCAPTCHA.layer.borderWidth = 1.0;
} /**
* 倒计时
*/
- (void)countDown {
//全局并发队列
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, );
//主队列;属于串行队列
dispatch_queue_t mainQueue = dispatch_get_main_queue(); //定时循环执行事件
//dispatch_source_set_timer 方法值得一提的是最后一个参数(leeway),他告诉系统我们需要计时器触发的精准程度。所有的计时器都不会保证100%精准,这个参数用来告诉系统你希望系统保证精准的努力程度。如果你希望一个计时器每5秒触发一次,并且越准越好,那么你传递0为参数。另外,如果是一个周期性任务,比如检查email,那么你会希望每10分钟检查一次,但是不用那么精准。所以你可以传入60,告诉系统60秒的误差是可接受的。他的意义在于降低资源消耗。
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, , , globalQueue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{ //计时器事件处理器
NSLog(@"Event Handler");
if (_surplusSecond <= ) {
dispatch_source_cancel(timer); //取消定时循环计时器;使得句柄被调用,即事件被执行
dispatch_async(mainQueue, ^{
_btnSendCAPTCHA.enabled = YES;
[_btnSendCAPTCHA setTitle:@"验证" forState:UIControlStateNormal]; _lblMessage.text = @"使用 GCD 实现倒计时效果";
_surplusSecond = kSurplusSecond;
});
} else {
_surplusSecond--;
dispatch_async(mainQueue, ^{
NSString *btnInfo = [NSString stringWithFormat:@"%ld秒", (long)(_surplusSecond + )];
_btnSendCAPTCHA.enabled = NO;
[_btnSendCAPTCHA setTitle:btnInfo forState:UIControlStateDisabled];
});
}
});
dispatch_source_set_cancel_handler(timer, ^{ //计时器取消处理器;调用 dispatch_source_cancel 时执行
NSLog(@"Cancel Handler");
});
dispatch_resume(timer); //恢复定时循环计时器;Dispatch Source 创建完后默认状态是挂起的,需要主动恢复,否则事件不会被传递,也不会被执行
} - (IBAction)sendCAPTCHA:(id)sender {
_lblMessage.text = [NSString stringWithFormat:@"验证码发送成功,%d秒后可重新发送", kSurplusSecond]; [self countDown];
} @end

Main.storyboard

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="ufC-wZ-h7g">
<objects>
<viewController id="vXZ-lx-hvc" customClass="ViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="jyV-Pf-zRb"/>
<viewControllerLayoutGuide type="bottom" id="2fi-mo-0CV"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="kh9-bI-dsS">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="使用 GCD 实现倒计时效果" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="1Kh-pV-cfz">
<rect key="frame" x="200" y="289.5" width="200" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="rFe-Xb-ZSc">
<rect key="frame" x="240" y="510" width="120" height="50"/>
<constraints>
<constraint firstAttribute="width" constant="120" id="gVH-aT-gen"/>
<constraint firstAttribute="height" constant="50" id="jJP-Vc-fpy"/>
</constraints>
<state key="normal" title="验证">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="sendCAPTCHA:" destination="vXZ-lx-hvc" eventType="touchUpInside" id="I6T-s9-9H6"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="centerX" secondItem="rFe-Xb-ZSc" secondAttribute="centerX" id="CoE-CP-eDN"/>
<constraint firstAttribute="centerY" secondItem="1Kh-pV-cfz" secondAttribute="centerY" id="bX4-jS-0xm"/>
<constraint firstAttribute="centerX" secondItem="1Kh-pV-cfz" secondAttribute="centerX" id="mKH-Zw-Utb"/>
<constraint firstItem="2fi-mo-0CV" firstAttribute="top" secondItem="rFe-Xb-ZSc" secondAttribute="bottom" constant="40" id="y3Q-IA-qIO"/>
</constraints>
</view>
<connections>
<outlet property="btnSendCAPTCHA" destination="rFe-Xb-ZSc" id="UFG-TS-ImX"/>
<outlet property="lblMessage" destination="1Kh-pV-cfz" id="gzx-3T-euc"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="x5A-6p-PRh" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>

输出结果:

 -- ::02.083 KMCountDown[:] Event Handler
-- ::03.087 KMCountDown[:] Event Handler
-- ::04.084 KMCountDown[:] Event Handler
-- ::05.086 KMCountDown[:] Event Handler
-- ::06.085 KMCountDown[:] Event Handler
-- ::07.085 KMCountDown[:] Event Handler
-- ::07.085 KMCountDown[:] Cancel Handler
上一篇:LENGTH() CHAR_LENGTH()


下一篇:Python 文件学习笔记