import UIKit
class ViewController: UIViewController {
var datePicker:UIDatePicker!
var leftTime:Int = 60
var timer : Timer!
var alert :UIAlertController!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
datePicker = UIDatePicker(frame: CGRect(x: 0, y: 100, width: 300, height: 200))
datePicker.datePickerMode = .countDownTimer
datePicker.countDownDuration = TimeInterval(self.leftTime)
datePicker.addTarget(self, action: #selector(datePickerClick(_:)), for: .valueChanged)
self.view.addSubview(datePicker)
let btn = UIButton(type: .roundedRect)
btn.frame = CGRect(x: 100, y: 400, width: 50, height: 50)
btn.setTitle("开始", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.setTitle("倒计时", for: .disabled)
btn.setTitleColor(UIColor.red, for: .disabled)
btn.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
self.view.addSubview(btn)
}
func btnClick(_ btn:UIButton)
{
//不响应点击
btn.isEnabled = false
// 获取该倒计时器的剩余时间
leftTime = Int(datePicker.countDownDuration);
// 禁用UIDatePicker控件和按钮
datePicker.isEnabled = false
alert = UIAlertController(title: "倒计时", message: "\(leftTime)", preferredStyle: .alert)
self.present(alert, animated: true, completion: {
//print("\(self.leftTime)")
})
// 启用计时器,控制每秒执行一次tickDown方法
timer = Timer.scheduledTimer(timeInterval:1, target: self, selector: #selector(timeStart), userInfo: nil, repeats: true)
}
func timeStart()
{
alert.message = "\(leftTime)"
// 将剩余时间减少1秒
leftTime = leftTime-1
// 修改UIDatePicker的剩余时间
datePicker.countDownDuration = TimeInterval(leftTime)
print(leftTime)
if leftTime<=0 {
alert.message = "时间到"
datePicker.isEnabled = true
// 取消定时器
timer.invalidate();
}
}
func datePickerClick(_ dateP:UIDatePicker)
{
print("\(dateP.date)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
使用UIDatePicker实现倒计时功能
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1. GCD一些常用概念介绍: 队列:用来存放任务任务:执行什么样的代码 2. 任务类型 GCD通过两个函数来分别...
- 在 Android 使用 Timer 做倒计时。实现开始 (start),取消 (cancel),暂停 (paus...