UIDatePicker object use to select the date and time, The UIDatePicker class have multiple rotate wheels and take value from that wheel and give one object of UIDatePicker and to get date from UIDatePicker object.
In this example, take one textFiled in which to open the datePicker using inputView. and adding toolbar in DatePicker.
Add the UITextField Delegate and drag it to view controller also.
Follow the below steps :
Step 1 : Adding one textFiled named textField_Date in ViewController and give IBOutlet connection and delegate. also take one UIDatePicker variable.
In this example, take one textFiled in which to open the datePicker using inputView. and adding toolbar in DatePicker.
Add the UITextField Delegate and drag it to view controller also.
Follow the below steps :
Step 1 : Adding one textFiled named textField_Date in ViewController and give IBOutlet connection and delegate. also take one UIDatePicker variable.
@IBOutlet weak var textField_Date: UITextField!
var datePicker : UIDatePicker!
Step 2 : The function pickUpDate to create UIDatePicker with ToolBar.
func pickUpDate(_ textField : UITextField){
// DatePicker
self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
self.datePicker.backgroundColor = UIColor.white
self.datePicker.datePickerMode = UIDatePickerMode.date
textField.inputView = self.datePicker
// ToolBar
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()
// Adding Button ToolBar
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.doneClick))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(ViewController.cancelClick))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar
}
Step 3 : Adding two buttons method which which is in ToolBar. One is doneClick and other is cancelClick.
func doneClick() {
let dateFormatter1 = DateFormatter()
dateFormatter1.dateStyle = .medium
dateFormatter1.timeStyle = .none
textField_Date.text = dateFormatter1.string(from: datePicker.date)
textField_Date.resignFirstResponder()
}
func cancelClick() {
textField_Date.resignFirstResponder()
}
Step 4 : Calling the pickUpDate function in UITextField delegate method.
func textFieldDidBeginEditing(_ textField: UITextField) {
self.pickUpDate(self.textField_Date)
}
Step 5 : outPut UIDatePicker with ToolBar in UITextField.
This comment has been removed by the author.
ReplyDelete