下面是代码示例:
// ViewController.swift
// CountDownTimerDemo
//
// Created by wsf on 16/1/26.
// Copyright © 2016年 wsf. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIAlertViewDelegate{
var datePickerView: UIDatePicker!;
var btnstart: UIButton!;
var leftTime: Int = 180;
var alertView: UIAlertView!;
var timer: NSTimer!;
override func viewDidLoad() {
super.viewDidLoad()
datePickerView = UIDatePicker(frame: CGRectMake(0.0,120.0,200.0,200.0));
self.datePickerView.datePickerMode = UIDatePickerMode.CountDownTimer;
datePickerView.locale = NSLocale(localeIdentifier: "zh_CN");
// 必须为60的整数倍,比如设置为100, 值自动变为60
self.datePickerView.countDownDuration = NSTimeInterval(leftTime);
datePickerView.addTarget(self,action: "timeChanged",forControlEvents: UIControlEvents.ValueChanged);
self.view.addSubview(datePickerView)
btnstart = UIButton(type: .System);
btnstart.frame = CGRect(x: 100,y: 400,width: 100,height: 100);
btnstart.setTitleColor(UIColor.redColor(),forState: UIControlState.Normal);
btnstart.setTitleColor(UIColor.grayColor(),forState: UIControlState.Disabled);
btnstart.setTitle("开始",forState: UIControlState.Normal);
btnstart.setTitle("倒计时中",forState: UIControlState.Disabled);
btnstart.clipsToBounds = true;
btnstart.layer.cornerRadius = 5;
btnstart.addTarget(self,action: "startClicked:",forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(btnstart);
}
func timeChanged() {
print("您选择倒计时间为: \(self.datePickerView.countDownDuration)");
}
/** 开始倒计时按钮点击 */
func startClicked(sender: UIButton) {
self.btnstart.enabled = false;
// 获取该倒计时器的剩余时间
leftTime = Int(self.datePickerView.countDownDuration);
// 禁用UIDatePicker控件和按钮
self.datePickerView.enabled = false;
// 创建一个UIAlertView对象(警告框),并确认,倒计时开始
alertView = UIAlertView();
alertView.title = "倒计时开始";
alertView.message = "倒计时开始,还有\(leftTime)秒...";
alertView.addButtonWithTitle("确定");
alertView.delegate = self;
// 显示UIAlertView组件
alertView.show();
// 启动计时器,控制每秒执行一次tickDown
timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1),target: self,selector: Selector("tickDown"),userInfo: nil,repeats: true);
}
func alertView(alertView: UIAlertView,clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 0 {
endTimer();
}
}
/** 关闭定时器 */
func endTimer() {
// 取消定时器
timer.invalidate();
// 启用UIDatePicker控件和按钮
self.datePickerView.enabled = true;
self.btnstart.enabled = true;
alertView.message = "时间到!";
}
/** 计时器每秒触发事件 */
func tickDown() {
alertView.message = "倒计时开始,还有\(leftTime)秒...";
// 剩余时间减少1秒
leftTime-- ;
// 修改UIDatePicker的剩余时间
self.datePickerView.countDownDuration = NSTimeInterval(leftTime);
print(leftTime);
// 如果剩余时间小于等于0
if (leftTime <= 0) {
endTimer();
}
}
}
上面的代码其实还是有个小bug的。
1
2
|
//必须为 60 的整数倍,比如设置为100,值自动变为 60
self
.ctimer.countDownDuration =
NSTimeInterval
(leftTime);
|
dispatch_async(dispatch_get_main_queue(),{
(
.leftTime);
})
|