Swift - 使用UIDatePicker实现倒计时功能

import UIKit
class ViewController: UIViewController {
var  ctimer:UIDatePicker!
var starBtn :UIButton!
var letfTime:Int = 180
var alertView : UIAlertView!
var timer :NSTimer!
override func viewDidLoad() {
    super.viewDidLoad()
 var SCREEN_WIDTH  = self.view.frame.width
  var SCREEN_HIGHT = self.view.frame.height
    ctimer = UIDatePicker(frame:CGRectMake(20,120,SCREEN_WIDTH-40,200))
    self.ctimer.datePickerMode = UIDatePickerMode.CountDownTimer
    //必须为 60 的整数倍,比如设置为100,值自动变为 60
    self.ctimer.countDownDuration = NSTimeInterval (letfTime)
    ctimer.addTarget(self, action: "ChangeValue", forControlEvents: UIControlEvents.ValueChanged)
    self.view.addSubview(ctimer)
    
    starBtn = UIButton (type: UIButtonType.System)
    starBtn.frame = CGRect(x: 100, y: 400, width: SCREEN_WIDTH-200, height: 100)
    starBtn.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
    starBtn.setTitleColor(UIColor.greenColor(), forState: UIControlState.Disabled)
    starBtn.setTitle("开始", forState: UIControlState.Normal)
    starBtn.setTitle("倒计时中", forState: UIControlState.Disabled)
    starBtn.clipsToBounds = true
    starBtn.layer.cornerRadius = 5
    starBtn.addTarget(self, action: "BtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(starBtn)
    
    

}
/**
 开始倒计时按钮点击
 */
func BtnClick(sender:UIButton){
 
    self.starBtn.enabled = false
    //获该取倒计时器的剩余时间
    letfTime = Int(self.ctimer.countDownDuration)
    // 禁用UIDatePicker控件和按钮
    self.ctimer.enabled = false
    // 创建一个UIAlertView对象(警告框),并确认,倒计时开始
    alertView = UIAlertView()
    alertView.title = "倒计时开始"
    alertView.message = "倒计时开始还有\(letfTime)秒......"
    alertView.addButtonWithTitle("确定")
    //显示UIAlerView组件
    alertView.show()
    // 启用计时器,控制每秒执行一次tickDown方法
    timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1), target: self, selector: Selector("tickDown"), userInfo: nil, repeats: true)
}

func tickDown(){
    
    alertView.message = "倒计时开始,还有\(letfTime)秒!"
    //将剩余时间减1秒
    letfTime -= 1
    //修改UIDatePicker的剩余时间
    //self.ctimer.countDownDuration = NSTimeInterval(letfTime)
    dispatch_async(dispatch_get_main_queue(), {
      self.ctimer.countDownDuration = NSTimeInterval(self.letfTime);
    })
    print(letfTime)
    //如果剩余时间小于等于0
    if(letfTime <= 0){
    //取消定时器
        
        timer.invalidate()
    //启用UIDatePicker控件和按钮
        ctimer.enabled = true
        starBtn.enabled = true
        alertView.message = "时间到"
    
    }
    
}

func ChangeValue(){
    print("您选择倒计时为:\(self.ctimer.countDownDuration)")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

你可能感兴趣的:(Swift - 使用UIDatePicker实现倒计时功能)