UIDatePicker倒计时 swift
//
// ViewController.swift
// UILabelTest
//
// Created by mac on 15/6/23.
// Copyright (c) 2015年 fangyuhao. All rights reserved.
//
import UIKit
class ViewController: UIViewController{
var ctimer:UIDatePicker!
var btnstart:UIButton!
var leftTime:Int = 180
var timer:NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
ctimer = UIDatePicker(frame: CGRectMake(0, 120.0, 200, 200))
self.ctimer.datePickerMode = UIDatePickerMode.CountDownTimer
//必须为60的整数倍,比如设置为100,值自动变为60
self.ctimer.countDownDuration = NSTimeInterval(leftTime)
ctimer.addTarget(self, action: "timerChanged", forControlEvents: UIControlEvents.ValueChanged)
self.view.addSubview(ctimer)
btnstart = UIButton.buttonWithType(UIButtonType.System) as UIButton
btnstart.frame = CGRect(x: 100, y: 400, width: 100, height: 100)
btnstart.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
btnstart.setTitleColor(UIColor.greenColor(), 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 timerChanged(){
println("倒计时:\(self.ctimer.countDownDuration)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func startClicked(sender:UIButton){
self.btnstart.enabled = false
//获取该倒计时器的剩余时间
leftTime = Int(self.ctimer.countDownDuration)
//禁用UIDatePicker控件和按钮
self.ctimer.enabled = false
var message = NSString(format: "倒计时开始,还有%d秒", leftTime)
let alertView = UIAlertView()
alertView.title = "倒计时开始"
alertView.message = message
alertView.addButtonWithTitle("确定")
alertView.show()
//启动计时器,控制每隔60s执行一次tickDown方法
timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1), target: self, selector: Selector("tickDown"), userInfo: nil, repeats: true)
}
func tickDown(){
leftTime -= 1
self.ctimer.countDownDuration = NSTimeInterval(leftTime)
println(leftTime)
if(leftTime<=0){
timer.invalidate()
self.ctimer.enabled = true
self.btnstart.enabled = true
let alertView = UIAlertView()
alertView.title = "时间到"
alertView.message = "时间到"
alertView.addButtonWithTitle("确定")
alertView.show()
}
}
}