自定义时间选择器,带有年月日时分的时间选择器

从此踏上了Swift的学习道路

在用Swift重写公司的项目中我计划先写一个工具类的三方库,主要集中我平时在项目中用到的工具类,点击查看库文件LYTools,目前还处于开始阶段,之前用的OC的比较方便的库在此慢慢都用Swift重写一遍。

正文

此处记录一个时间选择的工具,可以按照年月日时分选择,直接看效果图吧,图片前面是使用代码,这里使用的block,也可以选择使用代理方法

let pickView = LYDatePicker.init(component: 2)
pickView.ly_datepickerWithFiveComponent = {(date:Date,year:NSInteger,month:NSInteger,day:NSInteger,hour:NSInteger,minute:NSInteger) -> Void in
}
pickView.show()
image
let pickView = LYDatePicker.init(component: 3)
pickView.ly_datepickerWithFiveComponent = {(date:Date,year:NSInteger,month:NSInteger,day:NSInteger,hour:NSInteger,minute:NSInteger) -> Void in
}
pickView.show()
image
let pickView = LYDatePicker.init(component: 4)
pickView.ly_datepickerWithFiveComponent = {(date:Date,year:NSInteger,month:NSInteger,day:NSInteger,hour:NSInteger,minute:NSInteger) -> Void in
}
pickView.show()
image
let pickView = LYDatePicker.init(component: 5)
pickView.ly_datepickerWithFiveComponent = {(date:Date,year:NSInteger,month:NSInteger,day:NSInteger,hour:NSInteger,minute:NSInteger) -> Void in
}
pickView.show()
image

源码

首先需要一个Date的扩展文件“Date+Category.swift”,主要提供时间格式转换以及特殊时间取值等,下面列举使用到的扩展方法,想要查看更多可以到LYTools下载源码,好用请start,也欢迎来讨论技术

extension Date{
//本年
static func currentYear() -> NSInteger {
let components = calendar.dateComponents(unitFlags, from: Date())
return components.year!
}
//本月
static func currentMonth() -> NSInteger {
let components = calendar.dateComponents(unitFlags, from: Date())
return components.month!
}
//本日
static func currentDay() -> NSInteger {
let components = calendar.dateComponents(unitFlags, from: Date())
return components.day!
}
//当前小时
static func currentHour() -> NSInteger {
let components = calendar.dateComponents(unitFlags, from: Date())
return components.hour!
}
//当前分钟
static func currentMinute() -> NSInteger {
let components = calendar.dateComponents(unitFlags, from: Date())
return components.minute!
}
//时间字符串转换为日期
static func dateFromDateString(format: String, dateString: String) -> Date {
if format.isEmpty || dateString.isEmpty{
return Date()
}
let whiteSpace = CharacterSet.whitespacesAndNewlines
if format.trimmingCharacters(in: whiteSpace).isEmpty || dateString.trimmingCharacters(in: whiteSpace).isEmpty{
return Date()
}
if format == "0" || dateString == "0"{
return Date()
}
let dateFormat = DateFormatter()
dateFormat.dateFormat = format
let date = dateFormat.date(from: dateString)
if date != nil{
return date!
}
return Date()
}
static func dayCountInYearAndMonth(year:NSInteger, month:NSInteger) -> Int{
switch month {
case 1,3,5,7,8,10,12:
return 31
case 4,6,9,11:
return 30
case 2:
if year % 400 == 0 || (year % 100 != 0 && year % 4 == 0){
return 29
}else{
return 28
}
default:
return 0
}
}
}

下面是主要代码,时间显示上主要注意月,日的特殊处理,难点主要在于时间选择后如何能够避免某年某月中日的更换。此工具类通过代理或者block均可获取到选择的时间,下面的代码中直接复制使用会出现问题是因为我在写这个项目中使用了另一个工具类“UIView+Category.Swift”来直接赋值view的x或者y等,稍微修改后即可正常使用

import UIKit

@objc
protocol LYDatePickerDelete : NSObjectProtocol{
@objc func ly_datePickerChoosedTime(date:Date)
}

class LYDatePicker: UIControl {

var component : Int = 3

var delegate : LYDatePickerDelete?

var date = Date()
var year = Date.currentYear()
var month = Date.currentMonth()
var day = Date.currentDay()
var hour = Date.currentHour()
var minute = Date.currentMinute()

let yearEerliest = 1900//年份从1900年开始
let yearSum = 200//年份一共有200个选择

//点击确定后的block回调
typealias OneComponentBlock = (Date,NSInteger) -> Void
var ly_datepickerWithOneComponent : OneComponentBlock?
typealias TwoComponentBlock = (Date,NSInteger,NSInteger) -> Void
var ly_datepickerWithTwoComponent : TwoComponentBlock?
typealias ThreeComponentBlock = (Date,NSInteger,NSInteger,NSInteger) -> Void
var ly_datepickerWithThreeComponent : ThreeComponentBlock?
typealias FourComponentBlock = (Date,NSInteger,NSInteger,NSInteger,NSInteger) -> Void
var ly_datepickerWithFourComponent : FourComponentBlock?
typealias FiveComponentBlock = (Date,NSInteger,NSInteger,NSInteger,NSInteger,NSInteger) -> Void
var ly_datepickerWithFiveComponent : FiveComponentBlock?


fileprivate lazy var subView : UIView = {
let view = UIView(frame:CGRect(x:0,y:kScreenH - 230 - 44,width:kScreenW,height:230 + 44))
view.backgroundColor = UIColor.white
return view
}()

fileprivate lazy var pickerView : UIPickerView = {
let pickerView = UIPickerView(frame:CGRect(x:0,y:44,width:kScreenW,height:230))
pickerView.backgroundColor = UIColor.white
pickerView.delegate = self
pickerView.dataSource = self
return pickerView
}()

fileprivate lazy var sureBtn : UIButton = {
let btn = UIButton(type:.custom)
btn.setTitle("确定", for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
btn.setTitleColor(UIColor.RGBS(s: 33), for: .normal)
btn.addTarget(self, action: #selector(LYDatePicker.sureAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var cancleBtn : UIButton = {
let btn = UIButton(type:.custom)
btn.setTitle("取消", for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
btn.setTitleColor(UIColor.RGBS(s: 33), for: .normal)
btn.addTarget(self, action: #selector(LYDatePicker.cancleAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var titleLbl : UILabel = {
let lbl = UILabel()
lbl.textAlignment = .center
lbl.textColor = UIColor.RGBS(s: 33)
lbl.font = UIFont.systemFont(ofSize: 15.0)
lbl.text = "请选择时间"
return lbl
}()

init(component:Int) {
if component > 5{
self.component = 5
}else{
self.component = component
}

super.init(frame:CGRect(x:0,y:0,width:kScreenW,height:kScreenH))

self.setUpGlobalViews()
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

}

extension LYDatePicker{

func setUpGlobalViews() {
//1.点击背景取消选择
self.backgroundColor = UIColor.clear
let bg_btn = UIButton(frame:self.bounds)
bg_btn.backgroundColor = UIColor.black
bg_btn.alpha = 0.3
self.addSubview(bg_btn)
bg_btn.addTarget(self, action: #selector(LYDatePicker.cancleAction), for: .touchDown)

//2.时间选择器
self.subView.addSubview(self.pickerView)
//年是从1900开始计算,时和分都是从0开始计算,尾数为0,因此索引正常;月和日从1计算,因此索引要减去1
self.pickerView.selectRow(self.year - yearEerliest, inComponent: 0, animated: false)
if self.component > 1{
self.pickerView.selectRow(self.month - 1, inComponent: 1, animated: false)
}
if self.component > 2{
self.pickerView.selectRow(self.day - 1, inComponent: 2, animated: false)
}
if self.component > 3{
self.pickerView.selectRow(self.hour, inComponent: 3, animated: false)
}
if self.component > 4{
self.pickerView.selectRow(self.minute, inComponent: 4, animated: false)
}



//3.确定,取消按钮
let btnView = UIView(frame:CGRect(x:0,y:0,width:kScreenW,height:44))
self.cancleBtn.frame = CGRect(x:10,y:5,width:60,height:35)
self.titleLbl.frame = CGRect(x:80,y:5,width:kScreenW-160,height:35)
self.sureBtn.frame = CGRect(x:kScreenW-60-10,y:5,width:60,height:35)
let line = UIView(frame:CGRect(x:0,y:43,width:kScreenW,height:1))
line.backgroundColor = UIColor.RGBS(s: 240)
btnView.backgroundColor = UIColor.white
btnView.addSubview(cancleBtn)
btnView.addSubview(titleLbl)
btnView.addSubview(sureBtn)
btnView.addSubview(line)
self.subView.addSubview(btnView)
}


func sureAction() {

if (self.ly_datepickerWithOneComponent != nil) {
self.ly_datepickerWithOneComponent!(self.date,self.year)
}
if (self.ly_datepickerWithTwoComponent != nil) {
self.ly_datepickerWithTwoComponent!(self.date,self.year,self.month)
}
if (self.ly_datepickerWithThreeComponent != nil) {
self.ly_datepickerWithThreeComponent!(self.date,self.year,self.month,self.day)
}
if (self.ly_datepickerWithFourComponent != nil) {
self.ly_datepickerWithFourComponent!(self.date,self.year,self.month,self.day,self.hour)
}
if (self.ly_datepickerWithFiveComponent != nil) {
self.ly_datepickerWithFiveComponent!(self.date,self.year,self.month,self.day,self.hour,self.minute)
}

if (self.delegate != nil){
self.delegate?.ly_datePickerChoosedTime(date: self.date)
}

}


func cancleAction() {
UIApplication.shared.keyWindow?.addSubview(self)
UIApplication.shared.keyWindow?.bringSubview(toFront: self)

UIView.animate(withDuration: 0.25, animations: {
self.subView.y = kScreenH
}){(completion) in
self.removeFromSuperview()
}
}

func show() {
UIApplication.shared.keyWindow?.addSubview(self)
UIApplication.shared.keyWindow?.bringSubview(toFront: self)

self.subView.y = kScreenH
self.addSubview(self.subView)
UIView.animate(withDuration: 0.25, animations: {
self.subView.y = kScreenH - 230 - 44
})


}
}



extension LYDatePicker : UIPickerViewDelegate,UIPickerViewDataSource{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return self.component
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case 0:
return yearSum
case 1:
return 12
case 2:
return Date.dayCountInYearAndMonth(year: self.year, month: self.month)
case 3:
return 24
case 4:
return 60
default:
return 0
}
}

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let lbl = UILabel(frame:CGRect(x:0, y:0, width:kScreenW / 6.0, height:30))
lbl.textColor = UIColor.RGBS(s: 33)
lbl.textAlignment = .center
lbl.font = UIFont.systemFont(ofSize: 14.0)
switch component {
case 0:
lbl.text = "\(row + self.yearEerliest)年"
case 1:
lbl.text = "\(row + 1)月"
case 2:
lbl.text = "\(row + 1)日"
case 3:
lbl.text = "\(row)时"
case 4:
lbl.text = "\(row)分"
default:
lbl.text = ""
}

return lbl
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 || component == 1{
if self.component > 2{
let nextYear = self.pickerView.selectedRow(inComponent: 0)
let nextMonth = self.pickerView.selectedRow(inComponent: 1) + 1

if self.day == 31{
if [4,6,9,11].contains(nextMonth){
self.pickerView.selectRow(29, inComponent: 2, animated: false)
}else if nextMonth == 2{
if Date.dayCountInYearAndMonth(year: nextYear, month: nextMonth) == 28{
self.pickerView.selectRow(27, inComponent: 2, animated: false)
}else{
self.pickerView.selectRow(28, inComponent: 2, animated: false)
}
}
}else if self.day == 30 || self.day == 29{
if nextMonth == 2{
if Date.dayCountInYearAndMonth(year: nextYear, month: nextMonth) == 28{
self.pickerView.selectRow(27, inComponent: 2, animated: false)
}else{
self.pickerView.selectRow(28, inComponent: 2, animated: false)
}
}
}
}
}
self.resetDate()
}

func resetDate() {

self.year = self.pickerView.selectedRow(inComponent: 0) + yearEerliest
if self.component > 1{
self.month = self.pickerView.selectedRow(inComponent: 1) + 1
}
if self.component > 2{
self.day = self.pickerView.selectedRow(inComponent: 2) + 1
}
if self.component > 3{
self.hour = self.pickerView.selectedRow(inComponent: 3)
}
if self.component > 4{
self.minute = self.pickerView.selectedRow(inComponent: 4)
}

self.date = Date.dateFromDateString(format: "yyyy-MM-dd HH:mm", dateString: "\(self.year)-\(self.month)-\(self.day) \(self.hour):\(self.minute)")

self.pickerView.reloadAllComponents()

}
}

注明

还有OC版的同样的时间选择器,这里就不放出来了,如过有需要可联系我,坚持开源,免费分享

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容