You can use a date picker to allow a user to select a date, time value or both). You can also use it as a timer or stop clock. The date picker reports interactions to its associated target object.
UIDatePicker has various picker modes
- Time - The date picker displays hours, minutes, and (optionally) an AM/PM designation.
- Date - The date picker displays months, days of the month, and years.
- DateAndTime - The date picker displays both Date and Time.
- CountDownTimer - The date picker displays hour and minute values, for example [ 2 | 59 ].
//Create a DatePicker
let datePicker: UIDatePicker = UIDatePicker()
//Position date picker within a view
datePicker.frame = CGRect(x: 10, y: 50, width: self.view.frame.width, height: 200)
//Set Mode for Picker
datePicker.datePickerMode = .dateAndTime
//Set some of UIDatePicker properties
datePicker.timeZone = NSTimeZone.local
datePicker.backgroundColor = UIColor.white
//Set minimum and Maximum Dates
let calendar = Calendar(identifier: .gregorian)
var comps = DateComponents()
comps.month = 1
let maxDate = calendar.date(byAdding: comps, to: Date())
comps.month = 0
comps.day = -1
let minDate = calendar.date(byAdding: comps, to: Date())
datePicker.maximumDate = maxDate
datePicker.minimumDate = minDate
//add the picker to view
self.view.addSubview(datePicker)
Now lets create a Date Picker with Done and Cancel Buttons using a UIToolbar
![iOS Swift UIDatePicker](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPmxokkNHD9eYbuckfSNAk5LLHpjSJgTy9qcjweNGwZG7v_eV7-rDqzlOvgsiv6UdtnH1PRM-jQ20W0LuhZ7pvNo_hozFWSK2uOsDd6AkL8RH6zcaJUR8c4_MBr32fW8An0FpQ6YdADSs/s640/Simulator+Screen+Shot+-+iPhone+X+-+2019-03-26+at+10.09.19.png)
![iOS Swift UIDatePicker with Done and Cancel Buttons](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5nMubWTfBIRnPGlyJ7nNPT268_SieX-J7_zQaeSr_7Jod-VCgHy7VsC3gNBujws-DWKtC1zHhI7Y-m5xirV1o4V2D28ALYUTTRyROKZimyuqA5S6QX2qvDervPEwh7_nau5YgXH6u_JA/s640/Simulator+Screen+Shot+-+iPhone+X+-+2019-03-26+at+10.09.26.png)
![iOS Swift UIDatePicker UITextField](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUT-47N3CRSniVVpd2ka6DyH01OjWF0zn8y8i0-xu7Qun69ojTycHhoSgu8MgxoUmQYxx0Hc_WOhxh5AodF7KU3kWSIwIoerIOPQmzYtmD55fsCked-RO-OSWALbv9wWiUqJzkhSYSxdA/s640/Simulator+Screen+Shot+-+iPhone+X+-+2019-03-26+at+10.09.30.png)
import UIKit
class ViewController: UIViewController {
var pickerToolbar: UIToolbar?
var dateTextField: UITextField?
var datePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Main View"
//create the UITextfield to present the Date Picker
createUITextField()
//create the Toolbar for Cancel and Done buttons
createUIToolBar()
//set date picker mode
datePicker.datePickerMode = .date
//add toolbar to textField
dateTextField?.inputAccessoryView = pickerToolbar
//add datepicker to textField
dateTextField?.inputView = datePicker
}
func createUITextField(){
let myLabel = UILabel()
myLabel.textColor = UIColor.black
myLabel.text = "Date: "
myLabel.font = UIFont.systemFont(ofSize: 24.0)
myLabel.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(myLabel)
let myLabel2 = UILabel()
myLabel2.textColor = UIColor.brown
myLabel2.text = " (MM/DD/YY) "
myLabel2.font = UIFont.systemFont(ofSize: 24.0)
myLabel2.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(myLabel2)
dateTextField = UITextField()
dateTextField?.text = "Select a date ..."
dateTextField?.textColor = UIColor.black
dateTextField?.font = UIFont.systemFont(ofSize: 24.0)
dateTextField?.layer.borderColor = UIColor.lightGray.cgColor
dateTextField?.layer.borderWidth = 1.0
dateTextField?.layer.cornerRadius = 3;
dateTextField?.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(dateTextField!)
var allConstraints: [NSLayoutConstraint] = []
let views = ["view": view!, "myLabel": myLabel, "dateTextField": dateTextField, "myLabel2": myLabel2]
let horizontalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-[myLabel]-[dateTextField(200)]-[myLabel2]-(>=10)-|",
options: [.alignAllTop, .alignAllBottom], metrics: nil, views: views as [String : Any])
allConstraints += horizontalConstraints
var verticalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:|-(>=40)-[myLabel]", metrics: nil, views: views as [String : Any])
allConstraints += verticalConstraints
verticalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:|-(>=40)-[dateTextField]", metrics: nil, views: views as [String : Any])
allConstraints += verticalConstraints
verticalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:|-(>=40)-[myLabel2]", metrics: nil, views: views as [String : Any])
allConstraints += verticalConstraints
NSLayoutConstraint.activate(allConstraints)
}
func createUIToolBar() {
pickerToolbar = UIToolbar()
pickerToolbar?.autoresizingMask = .flexibleHeight
//customize the toolbar
pickerToolbar?.barStyle = .default
pickerToolbar?.barTintColor = UIColor.black
pickerToolbar?.backgroundColor = UIColor.white
pickerToolbar?.isTranslucent = false
//add buttons
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action:
#selector(cancelBtnClicked(_:)))
cancelButton.tintColor = UIColor.white
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action:
#selector(ViewController.doneBtnClicked(_:)))
doneButton.tintColor = UIColor.white
//add the items to the toolbar
pickerToolbar?.items = [cancelButton, flexSpace, doneButton]
}
@objc func cancelBtnClicked(_ button: UIBarButtonItem?) {
dateTextField?.resignFirstResponder()
}
@objc func doneBtnClicked(_ button: UIBarButtonItem?) {
dateTextField?.resignFirstResponder()
let formatter = DateFormatter()
formatter.dateStyle = .short
dateTextField?.text = formatter.string(from: datePicker.date)
}
}
Click here for more information on Swift Date formatting and conversion
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.