Swift - UIDatePicker

这篇博客介绍了如何在 Swift 中使用 UIDatePicker,包括纯代码和Storyboard两种方式的集成,并详细讲解了如何实现倒计时功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

纯代码使用:

import UIKit

class ViewController: UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        //创建DatePicker
        let datePicker = UIDatePicker()
        //设置位置
        datePicker.center = self.view.center
        //设置tag(可通过tag来获取其对象)
        datePicker.tag = 1
        //设置显示模式为日期时间
        datePicker.datePickerMode = UIDatePicker.Mode.dateAndTime
        //设置最大值,最小值
        datePicker.maximumDate = Date(timeInterval:3*24*60*60,since:Date())//设置最大值为现在时间往后三天以内
        datePicker.minimumDate = Date()//设置最小值为现在
        //更改地区文字
        datePicker.locale = Locale(identifier: "zh_CN")
        //设置文字颜色
        datePicker.setValue(UIColor.blue, forKey: "textColor")
        //添加到视图中
        self.view.addSubview(datePicker)
        //添加确定按钮
        let button = UIButton(frame: CGRect(x: 50, y: 400, width: 250, height: 50))
        button.backgroundColor = UIColor.yellow
        button.setTitle("确定", for: .normal)
        button.addTarget(self, action: #selector(ViewController.getValue), for: .touchUpInside)
        self.view.addSubview(button)
    }
    @objc func getValue()
    {
        let datePicker = self.view.viewWithTag(1)as! UIDatePicker//通过tag获取datePicker对象
        let date = datePicker.date//获取选定的值
        //初始化日期格式化对象
        let dateFormatter = DateFormatter()
        //设置日期格式化对象的具体格式
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        //将选定的值转换为string格式以设定格式输出
        let dateAndTime = dateFormatter.string(from: date)
        print(dateAndTime)
    }
}

stouryborad中使用:

首先我们将一个 UIDatePicker 控件和一个按钮直接添加到 Main.Storyboard 上。该按钮是为了点击时弹出提示框显示当前选择的日期和时间。
同时在 ViewController.swift 中使用 IBOutlet 建立起控件和事件的关联,具体代码如下

import UIKit
 
class ViewController: UIViewController {
     
    @IBOutlet  var dpicker:UIDatePicker!
    @IBOutlet  var btnshow:UIButton!
     
    override func viewDidLoad() {
        super.viewDidLoad()
    }
     
    @IBAction func showClicked(_ sender:UIButton)
    {
        let date = dpicker.date
         
        // 创建一个日期格式器
        let dformatter = DateFormatter()
        // 为日期格式器设置格式字符串
        dformatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
        // 使用日期格式器格式化日期、时间
        let datestr = dformatter.string(from: date)
         
        let message =  "您选择的日期和时间是:\(datestr)"
         
        // 创建一个UIAlertController对象(消息框),并通过该消息框显示用户选择的日期、时间
        let alertController = UIAlertController(title: "当前日期和时间",
                                                message: message,
                                                preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
}

实现倒计时功能

import UIKit
class ViewController: UIViewController{
    var datePicker:UIDatePicker!
    var startBtn:UIButton!//开始按钮
    var leftTime:Int = 0//剩余时间
    var alertController:UIAlertController!//提示框
    var timer:Timer!//时间器
    override func viewDidLoad() {
        super.viewDidLoad()
        datePicker = UIDatePicker(frame: CGRect(x: 0, y: 120, width: 200, height: 200))
        //设置模式为倒计时模式
        datePicker.datePickerMode = .countDownTimer
        self.view.addSubview(datePicker)
        
        startBtn = UIButton(type: .system)
        startBtn.frame = CGRect(x: 100, y: 400, width: 100, height: 100)
        startBtn.setTitleColor(UIColor.red, for: .normal)
        startBtn.setTitleColor(UIColor.green, for: .disabled)//当button为不启用时调用此代码
        startBtn.setTitle("开始", for: .normal)
        startBtn.setTitle("倒计时中", for: .disabled)//当button为不启用时调用此代码
        //对Button裁边
        startBtn.clipsToBounds = true
        //设置Button角半径
        startBtn.layer.cornerRadius = 5
        startBtn.addTarget(self, action: #selector(ViewController.startClicked), for: .touchUpInside)
        self.view.addSubview(startBtn)
    }
    
    @objc func startClicked(){
        //设置button不启用
        self.startBtn.isEnabled = false
        //获取Datepicker选择的时间
        leftTime = Int(datePicker.countDownDuration)
        //设置datepicker不启用
        self.datePicker.isEnabled = false
        //添加提示框
        alertController = UIAlertController(title: "系统提示", message:"倒计时开始,还有\(leftTime)秒", preferredStyle: .alert)
        let OK = UIAlertAction(title: "确定", style: .cancel, handler: nil)
        alertController.addAction(OK)
        present(alertController, animated: true, completion: nil)
        //Time Sources在计划的时间内或时间间隔内传递同步信息
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.tickDown), userInfo: nil, repeats: true)
    }
    
    @objc func tickDown(){
        alertController.message = "倒计时开始,还有\(leftTime)秒"
        
        leftTime -= 1
        self.datePicker.countDownDuration = TimeInterval(leftTime)
        if (leftTime <= 0){
            timer.invalidate()
            
            self.datePicker.isEnabled = true
            self.startBtn.isEnabled = true
            alertController.message = "时间到"
        }
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值