iOS|iOS/swift之UIDatePickView


1.***************UIDatePickView 简单使用*****************

/** UIDatePicker 使用: let datePick =LYBUIDateickview.init(frame: CGRect(x: 10, y: 0, width: WIDTH, height: 250)) datePick.selectDateBlock={ (dateStr)in print("\(dateStr)") } view.addSubview(datePick) */ import UIKitclass LYBUIDateickview: UIView {var datePicker:UIDatePicker! var dateString:String="" //定义一个block返回选择是时间 var selectDateBlock:(String)->()={ (String)in} override init(frame: CGRect) { super.init(frame:frame) createDatePickView(frame: frame) }required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }func createDatePickView(frame: CGRect){ let buttonView=UIView.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH, height: 50)) addSubview(buttonView) let cancelBtn=UIButton.init(frame: CGRect.init(x: 20, y: 0, width: 100, height: 50)) cancelBtn.setTitle("取消", for: UIControl.State.normal) cancelBtn.tag=10 cancelBtn.addTarget(self, action: #selector(sureOrcanceBtnClick), for: UIControl.Event.touchUpInside) buttonView.addSubview(cancelBtn)let sureBtn=UIButton.init(frame: CGRect.init(x: WIDTH-150, y: 0, width: 100, height: 50)) sureBtn.setTitle("确定", for: UIControl.State.normal) sureBtn.tag=11 sureBtn.addTarget(self, action: #selector(sureOrcanceBtnClick), for: UIControl.Event.touchUpInside) buttonView.addSubview(sureBtn) //创建日期选择器 datePicker = UIDatePicker(frame: CGRect(x:0, y:50, width:WIDTH, height:frame.size.height-50)) //将日期选择器区域设置为中文,则选择器日期显示为中文 datePicker.locale = Locale(identifier: "zh_CN") //文本显示的颜色 datePicker.setValue(UIColor.white, forKey: "textColor") datePicker.datePickerMode = .date//只显示日期 //datePicker.datePickerMode = .time//只显示时间datePicker.minimumDate=Date.init(timeIntervalSince1970: 60*60*24*365*5)//最小显示时间 datePicker.maximumDate=Date.init(timeInterval: 60*60*24*365*50, since: Date.init())//最大显示时间 //注意:action里面的方法名后面需要加个冒号“:”----有确定按钮可以不要这个监听 //datePicker.addTarget(self, action: #selector(dateChanged), //for: .valueChanged) self.addSubview(datePicker) }//确认或取消按钮 @objc func sureOrcanceBtnClick(sender:UIButton){ switch sender.tag { case 10://取消 self.removeFromSuperview() breakcase 11://确认 //更新提醒时间文本框 let formatter = DateFormatter() //日期样式 formatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss" selectDateBlock(formatter.string(from: datePicker.date)) self.removeFromSuperview() breakdefault: break} }//日期选择器响应方法 @objc func dateChanged(datePicker : UIDatePicker){ ////更新提醒时间文本框 //let formatter = DateFormatter() ////日期样式 //formatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss" //print(formatter.string(from: datePicker.date)) }}

【iOS|iOS/swift之UIDatePickView】

    推荐阅读