I have a datePicker that updates my textField. Once the textField data changes is supposed to perform actions(such as verifying data). The problem is that after the datePicker updates the textField, the textField does not perform any actions, regardless of what action event I am using on the textField, such as .ValueChanged.I cannot figure out what the problem is. I noticed though, that if I am to type something in the textField, the action event works.
Here's my code:
class CustomTextField: UITextField, UITextFieldDelegate {
var customDelegate : CustomTextFieldDelegate?
enum type {
case standard
case date
}
var textFieldType : type = .standard {
didSet{
switch self.textFieldType {
case .standard:
break
case .date:
let datePicker = UIDatePicker.MMMddyyyy
self.inputView = datePicker
datePicker.addTarget(self, action: #selector(refreshOnDatePicker(_:)), for: .valueChanged)
self.addTarget(self, action: #selector(checkFieldInput), for: .applicationReserved)
break
}
}
}
#objc private func checkFieldInput(sender: CustomTextField){
guard let fieldInput = self.text else { return }
switch sender.textFieldType {
case .standard:
break
case .date:
customDelegate?.isTextFieldVerified = !fieldInput.isEmpty
break
}
}
#objc private func refreshOnDatePicker(_ selector: UIDatePicker){
self.text = selector.date.formattedMMMMddyyyy
}
}
fileprivate extension UIDatePicker {
class var MMMddyyyy : UIDatePicker {
let currentDate: NSDate = NSDate()
let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
calendar.timeZone = NSTimeZone(name: "UTC")! as TimeZone
let components: NSDateComponents = NSDateComponents()
components.calendar = calendar as Calendar
components.year = -100
let minDate: NSDate = calendar.date(byAdding: components as DateComponents, to: currentDate as Date, options: NSCalendar.Options(rawValue: 0))! as NSDate
let dp = UIDatePicker()
dp.datePickerMode = .date
dp.minimumDate = minDate as Date
dp.maximumDate = currentDate as Date
dp.backgroundColor = UIColor.white
return dp
}
}
fileprivate extension Date {
/// date formatted type "MMMM dd, yyyy"
var formattedMMMMddyyyy: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd, yyyy"
return formatter.string(from: self)
}
}
Try this
#objc private func refreshOnDatePicker(_ selector: UIDatePicker){
self.text = selector.date.formattedMMMMddyyyy
self.checkFieldInput(sender:self)
}
Related
If you look at the iPhone alarm app I can see that if I don't set the time in the date picker, the alarm is set to the current time.
#IBAction func selectAlarm(_ sender: Any) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
let date = dateFormatter.string(from: datePicker.date)
print("date : \(date)")
}
The above code outputs the time set when the datePicker is moved. How to output current time as default without moving datePicker as above?
Try this
#IBAction func selectAlarm(_ sender: Any) {
let newDatePicker = UIDatePicker()
newDatePicker.date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let currentTime = dateFormatter.string(from: newDatePicker.date)
print("time : \(currentTime)")
self.yourTextField.text = currentTime
}
Put the datePicker.date outside the func selectAlarm(), eg: in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
datePicker.datePickerMode = .time
datePicker.date = Date()
}
The date Picker works and gives date even without moving datePicker. I have tested it.
#IBAction func getCurrentTime() {
var formatter = DateFormatter()
formatter.dateFormat = "DD/MM/YY"
var dd = formatter.string(from: datePicker.date)
print(dd)
}
Problem is with your code.
In my app I have a form that has a textField that pulls up a UIDatePicker when clicked. When I select a new date from the UIDatePicker the textField does not update.
When debugging it seems like when a new date is selected the action isn't registered and it just sends over the same date.
Below is my code (Which I am planning on refactoring/cleaning up after resolving this issue)
import UIKit
import RealmSwift
class ClientDetailsViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
let realm = try! Realm()
//Create Picker Views
let dateAppointedPickerView = UIDatePicker()
#IBOutlet weak var clientDateAppointedText: UITextField!
var selectedClient : Client? {
//Everything in the did set function will happen as soon as this variable is set with a value
didSet {
loadClientDetails()
}
}
override func viewDidLoad() {
super.viewDidLoad()
//Assign Picker Views
setPickerViews()
//Assign Picker View Settings
setPickerViewSettings()
//Assign Picker View Delegates
setDelegates()
}
//MARK: - Date Format Method
func formatDateToString(_ date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
dateFormatter.locale = Locale.current
let formattedDate = dateFormatter.string(from: date)
return formattedDate
}
func formatStringToDate(_ dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
dateFormatter.locale = Locale.current
let formattedDate = dateFormatter.date(from: dateString)
return formattedDate!
}
func loadClientDetails() {
loadViewIfNeeded()
clientDateAppointedText.text = formatDateToString((selectedClient?.dateAppointed)!)
}
//Send textfield/picker data to database
func textFieldDidEndEditing(_ textField: UITextField) {
var clientData : String = ""
guard let currentClient = selectedClient else {fatalError()}
switch textField {
case clientDateAppointedText:
clientData = "clientDateAppointedText"
updateClientDetails(currentClient, clientData)
default:
print("Did not edit anything")
}
}
//MARK: - Data Manipulation Methods
func updateClientDetails(_ clientInfo: Client,_ clientString: String) {
let editClient : String = clientString
do {
try realm.write {
switch editClient {
case "clientDateAppointedText":
clientInfo.dateAppointed = formatStringToDate(clientDateAppointedText.text!)
default:
print("Unable to edit client information")
}
}
} catch {
print("Unable to save client details")
}
}
I expect the Date Picker to update the textview every time a new date is chosen and for the value to be passed to the database to be updated. The actual result is that the value passed is the same date over and over again.
Steps to do it:
First intialize pickerview
var datePickerView:UIDatePicker = UIDatePicker()
Create action of textfield through storyboard i.e "Editing Did Begin"
#IBAction func textEditing(_ sender: UITextField)
{
isPickUpSelected = true
datePickerView = UIDatePicker()
datePickerView.minimumDate = Date()
datePickerView.date = selectedPickupDate
datePickerView.datePickerMode = UIDatePickerMode.date
sender.inputView = datePickerView
datePickerView.addTarget(self, action:
#selector(TUGBestDealVC.datePickerValueChanged), for:
UIControlEvents.valueChanged)
self.addToolBar(picker: datePickerView, textField: sender)
}
Write addToolbar function to customize datepicker:
func addToolBar(picker: UIDatePicker, textField: UITextField)
{
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor.darkGray
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: TUGHelpers().getLocalisedString(strKey:
"DONE"),style: .plain, target: self,
action:#selector(TUGBestDealVC.doneClick(sender:)))
doneButton.tag = picker.tag
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target:
nil,action: nil)
let cancelButton = UIBarButtonItem(title:"Cancel", style: .plain, target: self,
action:#selector(TUGBestDealVC.cancelClick(sender:)))
cancelButton.tag = picker.tag+4
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar
}
Track action of datepicker change date:
func datePickerValueChanged(sender:UIDatePicker)
{
self.setPickupDate(date: sender.date)
}
Here is done action of datepickerview:
#objc func doneClick(sender: UIButton)
{
self.setPickupDate(date: datePickerView.date)
dateTxt.resignFirstResponder()
}
Here is cancel action of datepickerview:
#objc func cancelClick(sender: UIButton)
{
dateTxt.resignFirstResponder()
}
Here you will get the date of pickerview:
func setPickupDate(date: Date)
{
print(date)
}
The same code you can update in the database every time
Enjoy, Happy coding.
When I select the date the app stops responding. I want to select the date and show it in a textfield without pressing a done button. So I want to see date in live.
How do I print the age based on the selected Date picker on a TextField?
import UIKit
import Firebase
class SignUpEmailSegue0: UIViewController {
#IBOutlet weak var dateBirthday: UITextField!
#IBAction func dateBirthdayEdit(_ sender: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleDatePicker), for: UIControlEvents.valueChanged)
}
#objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MMM/yyyy"
dateBirthday.text = dateFormatter.string(from: sender.date)
}
}
Try changing your code as follows - using #selector() and exposing your function to #objc
datePickerView.addTarget(self, action: #selector(handleDatePicker), for: UIControlEvents.valueChanged)
#objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateBirthday.text = dateFormatter.string(from: sender.date)
}
To answer your second question of how to get the age:
let gregorian = Calendar(identifier: .gregorian)
let ageComponents = gregorian.dateComponents([.year], from: sender.date, to: Date())
if let age = ageComponents.year {
print(age)
}
I have two datepickers that contains time with format 7:00 AM and 8:00 PM for login and logout. These times may vary. I wanted to change the logout time and tried to use the login time as the minimum time but my code does not work, I can still select time like 1:00 AM or 6:00 AM as logout.
This is the code in my ViewDidLoad
if let actualLoginText = loginTextField.text {
let start = actualLoginText
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
formattedTime = formatter.date(from: start)!
}
And this is the code of my logout picker
#objc func timeOutPickerValueChanged(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
timeOutPicker.minimumDate = Calendar.current.date(byAdding: .minute, value: 5, to: formattedTime)
logoutTextField.text = formatter.string(from: sender.date)
}
I also tried this but still doesn't work
if let actualLoginText = loginTextField.text {
let start = actualLoginText
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
formattedTime = formatter.date(from: start)!
}
Thank you.
When working with dates / times, work with Date objects, not strings. The "string representation" should only be used to display the date/time to the user, not when manipulating the values.
Here is a simple example (assuming you have added two UIDatePickers and connected their Value Changed events). On load, it initializes the timeInPicker to the current date/time. Any time you select a new "Time In", the timeOutPicker.minimumDate is set to 5-minutes from the selected time, and the timeOutPicker.maximumDate is set to 8-hours from the minimum time:
class ViewController: UIViewController {
#IBOutlet weak var timeInPicker: UIDatePicker!
#IBOutlet weak var timeOutPicker: UIDatePicker!
let dateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateStyle = .short
df.timeStyle = .short
return df
}()
override func viewDidLoad() {
super.viewDidLoad()
// Initialize the TimeIn and TimeOut pickers to the current Date/Time
let now = Date()
updateTimeOutPicker(now)
}
func updateTimeOutPicker(_ withStartDateTime: Date) -> Void {
// add 5 minutes to the selected "In" time to get the "minimum time" for the Out Picker
guard let minDateTime = Calendar(identifier: .gregorian).date(byAdding: .minute, value: 5, to: withStartDateTime) else { return }
// add 8 hours to the to get the "maximum time" for the Out Picker
guard let maxDateTime = Calendar(identifier: .gregorian).date(byAdding: .hour, value: 8, to: minDateTime) else { return }
timeOutPicker.minimumDate = minDateTime
timeOutPicker.maximumDate = maxDateTime
print("New Min Out Time:", dateFormatter.string(from: minDateTime))
print("New Max Out Time:", dateFormatter.string(from: maxDateTime))
print()
}
#IBAction func timeInPickerValueChanged(_ sender: UIDatePicker) {
print("Selected In Time:", dateFormatter.string(from: sender.date))
print()
updateTimeOutPicker(sender.date)
}
#IBAction func timeOutPickerValueChanged(_ sender: UIDatePicker) {
print("Selected Out Time:", dateFormatter.string(from: sender.date))
print()
}
}
The login and logout time strings were pulled up from database. And when I don't edit the login textfield it's data remains as string since there was no value change, so I'm forced to use a string value as reference to my logout picker.
the result login being: 1999-12-31 23:00:00 +0000
and logout: 2018-01-04 22:24:20 +0000
this is the reason why using the login as my minimum time didn't work
so here's what I did, I added the current date so I can use it.
#objc func timeOutPickerValueChanged(sender: UIDatePicker) {
if let actualLoginText = loginTextField.text {
let date = Date()
let start = actualLoginText
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let nowTime = formatter.string(from: date)
let concat = nowTime + " " + start
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
formattedTime = dateFormatter.date(from: concat)!
}
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
timeOutPicker.minimumDate = Calendar.current.date(byAdding: .minute, value: 5, to: formattedTime)
logoutTextField.text = formatter.string(from: sender.date)
}
In my code below i have implemented a date picker to be the subview of my textfield. I am stuck on the function; 'verifyAge'. The if statement in the function is working fine and will change the textField colour when the Date Picker date is above or below the specified date. But it only works to the corresponding year But does not Work to the exact Day. I have tried searching for the past two days and couldn't find a solution to my exact problem.
class AgeConfirmViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var txtAgeConfirmation: UITextField!
let datePicker: UIDatePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
txtAgeConfirmation.delegate = self
createDatePicker()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
txtAgeConfirmation.inputView = datePicker
datePicker.addTarget(self, action: #selector(self.datePickerChanged(sender:)), for: .valueChanged)
}
func datePickerChanged(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.timeStyle = .none
formatter.dateStyle = .long
txtAgeConfirmation.text = formatter.string(from: sender.date)
verifyAge()
}
func createDatePicker() {
datePicker.datePickerMode = .date
datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: 0, to: Date())
}
func verifyAge() {
let dateOfBirth = datePicker.date
let today = Date()
let gregorian = NSCalendar(identifier: NSCalendar.Identifier.gregorian)
let age = gregorian?.components([.month, .day, .year], from: dateOfBirth, to: today, options:[])
if (age?.year)! < 21 {
txtAgeConfirmation.textColor = UIColor.red
} else if (age?.year)! > 21 {
txtAgeConfirmation.textColor = UIColor.black
}
}
Simple solution, ignore day and month:
let gregorian = Calendar(identifier: .gregorian)
let ageComponents = gregorian.dateComponents([.year], from: dateOfBirth, to: Date())
let age = ageComponents.year!
txtAgeConfirmation.textColor = age < 21 ? .red : .black
Or if you want to ignore the time
let ageComponents = calendar.dateComponents([.year], from: calendar.startOfDay(for: dateOfBirth), to: calendar.startOfDay(for: Date()))
In Swift 3 there are less question and exclamation marks by using native Calendar struct.
The age exclamation mark after year is absolutely safe because the year component is clearly specified.