swift not updating textfield.text using UIDatePicker - ios

In swift, I have a textField programmatically declared.
override func viewDidLoad() {
super.viewDidLoad()
textField3.delegate = self
textField3.returnKeyType = UIReturnKeyType.Next;
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)
textField3.inputView = datePicker
}
func handleDatePicker(sender: UIDatePicker) {
textField3.text = dateFormatter.stringFromDate(sender.date)
}
All the other questions I've found similar to this deal with interface builder, and haven't helped. How would i fix this programmatically?

Xcode 9 • Swift 4
#objc func handleDatePicker(_ datePicker: UIDatePicker) {
textField3.text = datePicker.date.formatted
}
override func viewDidLoad() {
super.viewDidLoad()
datePicker.addTarget(self, action: #selector(handleDatePicker), forControlEvents: .valueChanged)
}
extension Date {
static let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
return formatter
}()
var formatted: String {
return Date.formatter.string(from: self)
}
}

Swift 3 version of #Leo Dabus answer:
func handleDatePicker(sender: UIDatePicker) {
textField3.text = datePicker.date.formatted
}
override func viewDidLoad() {
super.viewDidLoad()
datePicker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: UIControlEvents.valueChanged)
}
extension Date {
var formatted: String {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
return formatter.string(from: self as Date)
}
}

In, Swift 4
confirm to UITableViewDelegate
make txtFChequeDate.delegate = self
func textFieldDidBeginEditing(_ textField: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .date
txtFChequeDate.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
if txtFChequeDate.text == "" {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
txtFChequeDate.text = dateFormatter.string(from: Date())
}
}
#objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
txtFChequeDate.text = dateFormatter.string(from: sender.date)
}

Related

Question about setting datePicker time in Swift

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.

How do I print the age based on the selected date picker on a text field?

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)
}

UITextField not triggering action event upon UIDatePicker action event

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)
}

DatePicker - How to display date Month name in three characters instead of number

This is my first ever attempt at Swift or an iPhone app, so needless to say I'm not sure how to do many things at this point.
I want to show the date like this in my textfield
02 Feb 2016
But right now it displays like this
2/7/16
here is my code
#IBAction func dateTextFieldBeginEditing(sender: UITextField) {
// let datePickerView:UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
departureDateTextField.text = dateFormatter.stringFromDate(sender.date)
}
Set date format like this!! This will give you date like 02 Feb 2016.
Also remove dateStyle and timeStyle property from your code.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
dateFormatter.stringFromDate(NSDate())
This gives me output as 09 FEB 2016
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
let dateString = dateFormatter.stringFromDate(sender.date)
departureDateTextField.text = dateString
}
1) Add an Extension of NSDate
extension NSDate {
func dateStringWithFormat(format: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.stringFromDate(self)
}
}
2) Make two public variables
var datePicker:UIDatePicker?
let formatter = NSDateFormatter()
3) Add to UIDatePicker
let dateString = NSDate().dateStringWithFormat("yyyy-MM-dd")
print("Today's Date: "+dateString)
datePicker?.date = formatter.dateFromString(dateString)!
func datePicker(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
//// dd MMM yyyy == 02 Feb 2016
let dateData = dateFormatter.stringFromDate(sender.date)
departureDateTextField.text = dateData
}
let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .NoStyle)
print(timestamp)
override func viewDidLoad()
{
super.viewDidLoad()
self.datePicker.backgroundColor = .white
self.datePicker.datePickerMode = .date
let loc = Locale.init(identifier: "pt-BR")
var calendar = Calendar.current
calendar.locale = loc
self.datePicker.calendar = calendar
self.datePicker.locale = loc
self.datePicker.addTarget(self, action: #selector(ViewController.handleDatePicker), for: UIControl.Event.valueChanged)
}
#objc func handleDatePicker()
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let loc = Locale.init(identifier: "pt-BR")
dateFormatter.locale = loc
print(dateFormatter.string(from: self.datePicker.date))
}

Convert String to NSDate when using DatePicker and TextField

I'm using a textfield that uses a datePicker instead of a keyboard. It displays the format as a string that looks like this 'May 31, 2015 at 12:30'(taken from the println(delivery.text) function.) I want to change the date to NSDate, so I can compare to current date. Any suggestions?
#IBOutlet weak var pickUp: UITextField!
#IBOutlet weak var delivery: UITextField!
let dateFormat: NSDateFormatter = NSDateFormatter()
let datePicker: UIDatePicker = UIDatePicker()
let dateFormat2: NSDateFormatter = NSDateFormatter()
let datePicker2: UIDatePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
dateFormat.dateStyle = NSDateFormatterStyle.LongStyle
dateFormat.timeStyle = NSDateFormatterStyle.LongStyle
datePicker.datePickerMode = UIDatePickerMode.DateAndTime
datePicker.addTarget(self, action: Selector("updateDateField:"), forControlEvents:UIControlEvents.ValueChanged)
pickUp.inputView = datePicker
dateFormat2.dateStyle = NSDateFormatterStyle.LongStyle
dateFormat2.timeStyle = NSDateFormatterStyle.LongStyle
datePicker2.datePickerMode = UIDatePickerMode.DateAndTime
datePicker2.addTarget(self, action: Selector("updateDateField:"), forControlEvents:UIControlEvents.ValueChanged)
delivery.inputView = datePicker2
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.toolbarHidden = false
self.tabBarController?.tabBar.hidden = true
}
func updateDateField(sender: UIDatePicker) {
if sender == datePicker
{
pickUp.text = dateFormat.stringFromDate(sender.date)
}
if sender == datePicker2
{
delivery.text = dateFormat2.stringFromDate(sender.date)
}
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy 'at' h:mm:ss a"
if let date = dateFormatter.dateFromString("May 31, 2015 at 12:30:15 PM") {
println(date)
}
if you need some reference for date formatting you can use this one:
You can try using the DateFormatter to format your string into a date and then pulling the NSDate object out like so. In your case, something like this would probably suit your needs.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM d, yyyy at H:mm"
let date = dateFormatter.dateFromString(//insert string here)
Refer to the original documentation if you have further questions or this handy guide for formatting guidelines.

Resources