Description
We need to create Date Picker as input view for textfield. It is simple - just create
UIDatePicker object and assign it as inputView of textfield. Also we need to create toolbar for this Date Picker. Toolbar should contains two buttons: Cancel and Done. By clicking Cancel just close Date Picker and by clicking Done put selected date in textfield. Also hide date picker by clicking anywhere on the view (it can be done by implementing method
touchesBegan).
Full Code
import UIKit
class ViewController: UIViewController {
@IBOutlet var dateLabel: UILabel!
@IBOutlet var dateTextField: UITextField!
let datePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
self.dateTextField.inputView = self.datePicker
self.dateTextField.inputAccessoryView = self.createToolbar()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func createToolbar() -> UIToolbar {
let toolbar = UIToolbar()
let cancelBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain,
target: self, action: #selector(hideDatePicker))
let flexBarButtonItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: nil, action: nil)
let doneBarButtonItem = UIBarButtonItem(title: "Done", style: .done,
target: self, action: #selector(doneDatePicker))
toolbar.setItems([cancelBarButtonItem, flexBarButtonItem, doneBarButtonItem],
animated: false)
toolbar.barStyle = .default
toolbar.tintColor = UIColor.black
toolbar.isTranslucent = false
toolbar.isUserInteractionEnabled = true
toolbar.sizeToFit()
return toolbar
}
@objc func hideDatePicker() {
self.view.endEditing(true)
}
@objc func doneDatePicker() {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
let selectedDate = self.datePicker.date
self.dateTextField.text = dateFormatter.string(from: selectedDate)
self.view.endEditing(true)
}
}
Screens
There are many articles circulating on internet that exaggerate about Custom Designed Websites. But your article is an exception that made me understand it without any difficulty.
ReplyDeleteThank you for sharing this important and useful information in this article. Best Custom Websites
ReplyDeleteYour article is unbelievable with precise knowledge. I can see a lot of research behind that and that is beyond my expectations.
ReplyDeleteCreate Your Own Website \
This is a great article! Thank you very much. I really need these suggestions. An in-depth explanation is of great benefit. Incredibly inspiring to see how you write. Custom Website
ReplyDeleteThis is a fantastic article. Your essay is quite simple to comprehend. Thank you for sharing this informative information with us.
ReplyDeleteSearch Engine Marketing Agency