How To Reference UIAlert Textfield - Swift - swift

I have an alert which has a datepicker in a textfield. I want to reference this textfield to the objc for added properties, how would I be able to do this? I tried to use the following method but it does not work with error 'alert not in scope'.
Alert
#IBAction func info(_ sender: Any) {
let alert9 = UIAlertController (title: "Add Your Info", message: nil, preferredStyle: UIAlertController.Style.alert)
let cancel9 = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)
alert9.addAction(cancel9)
alert9.addTextField { (textfieldDate: UITextField) in
textfieldDate.placeholder = "Date"
self.datePickerWeight = UIDatePicker()
self.datePickerWeight!.preferredDatePickerStyle = .wheels
self.datePickerWeight?.datePickerMode = .date
self.datePickerWeight?.addTarget(self, action: #selector(ViewController.dateChangedInfo(datePicker:)), for: .valueChanged)
textfieldDate.inputView = self.datePickerInfo
let dateFormatterWeight = DateFormatter()
dateFormatterInfo.dateFormat = "EEEE, MMM d, yyyy"
let todayDateInfo = dateFormatterInfo.string(from: Date.init())
textfieldDate.text = todayDateInfo
}
alert9.addTextField { (textfieldAddInfo: UITextField) in
textfieldAddInfo.placeholder = "Info"
textfieldAddInfo.keyboardType = .decimalPad
}
let ok9 = UIAlertAction(title: "Save", style: UIAlertAction.Style.default) { (action: UIAlertAction) in print("OK")
let textfieldDate = alert9.textFields![0]
let textfieldAddInfo = alert9.textFields![1]
}
dateChangedInfo objC
#objc func dateChangedInfo(datePicker: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
let stringDate = dateFormatter.string(from: datePicker.date)
let textfieldDate = alert9.textFields?[0] // Cannot find 'alert9' in scope
self.textfieldDate.text = stringDate
self.fetchData(for: stringDate)
}

Make alert9 an instance variable.
var alert9: UIAlertController?
#IBAction func info(_ sender: Any) {
alert9 = UIAlertController (title: "Add Your Info", message: nil, preferredStyle: UIAlertController.Style.alert)
...
}

Related

How to send Date and Time separately to backend in swift?

fromDateLabel.text getting date and time from datepicker.. which i need to send date and time seperatedly to backend
when i do DateFormatter date is coming correctly but in time, only two digit values are working means time taking 10, 11, 12 O'Clocks. if i take 1,2,3,4,5 its not working
code: here single digit time not working
var fromDateArr = fromDateLabel.text!.components(separatedBy: ",")
fromDate = fromDateArr[0]
fromTime = fromDateArr[1].replacingOccurrences(of: " ", with: "")
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy"
let showDateFrom = inputFormatter.date(from: fromDate)
inputFormatter.dateFormat = "dd-MM-yyyy"
formateFromdate = inputFormatter.string(from: showDateFrom!)
print("formate from date \(formateFromdate)")
if i formate date and time like below nothing works
let fromDate = fromDateLabel.text!
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy, hh:mm:ssa"
guard let showDateFrom = inputFormatter.date(from: fromDate) else { return }
inputFormatter.dateFormat = "MM/dd/yyyy" // -> to get date only
formateFromdate = inputFormatter.string(from: showDateFrom)
print("from date: ", formateFromdate)
inputFormatter.dateFormat = "hh:mm a" // -> to get time only
formateFromTime = inputFormatter.string(from: showDateFrom)
print("from time")
How to send date and time separately to backend.. with 1 to 12hrs time
NOTE: if its 8 o clock then the out put time should be 08:15, not 8:15.. thats the issue.. please help me with code
Design
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var txtdate: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.txtdate.setInputViewDatePicker(target: self, selector: #selector(tapDone)) //1
}
#objc func tapDone() {
if let datePicker = self.txtdate.inputView as? UIDatePicker {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "MM/dd/yy, hh:mm a"
self.txtdate.text = dateformatter.string(from: datePicker.date)
}
self.txtdate.resignFirstResponder()
}
#IBAction func showClk(_ sender: Any) {
let fromDate = txtdate.text!
print(fromDate)
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "MM/dd/yy, hh:mm a"
guard let showDateFrom = inputFormatter.date(from: fromDate) else { return }
inputFormatter.dateFormat = "MM/dd/yyyy" // -> to get date only
let formateFromdate = inputFormatter.string(from: showDateFrom)
print("from date: ", formateFromdate)
inputFormatter.dateFormat = "hh:mm a" // -> to get time only
let formateFromTime = inputFormatter.string(from: showDateFrom)
print("from time" ,formateFromTime)
}
}
extension UITextField {
func setInputViewDatePicker(target: Any, selector: Selector) {
// Create a UIDatePicker object and assign to inputView
let screenWidth = UIScreen.main.bounds.width
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))//1
datePicker.datePickerMode = .date
self.inputView = datePicker
// Create a toolbar and assign it to inputAccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0))
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancel = UIBarButtonItem(title: "Cancel", style: .plain, target: nil, action: #selector(tapCancel))
let barButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
toolBar.setItems([cancel, flexible, barButton], animated: false)
self.inputAccessoryView = toolBar
}
#objc func tapCancel() {
self.resignFirstResponder()
}
}

Multiple UITextFields not displaying properly inside an UIAlertController

I need to display 4 UITextFields in an UIAlertController (Xcode 11.5). Did it as usual but the center UITextFields appear w/o border view image and it doesn't look well (I am adding a screenshot). I tried to set the UITextField Borderstyle, frame, but I can't get it right.
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var dayOfWeekField = UITextField()
var inicioTextField = UITextField()
var terminoTextField = UITextField()
var numeroDeCirugias = UITextField()
let alert = UIAlertController(title: "Agregar Nuevo Bloque", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Agregar", style: .default) { (action) in
let nuevoBloque = Bloques(context: self.context)
nuevoBloque.dia = dayOfWeekField.text!
nuevoBloque.inicio = inicioTextField.text!
nuevoBloque.termino = terminoTextField.text!
nuevoBloque.cirugias = Int16(numeroDeCirugias.text!)!
self.bloques.append(nuevoBloque)
self.saveBloques()
}
alert.addAction(action)
alert.addAction(UIAlertAction(title: "Cancelar", style: .destructive, handler: nil))
alert.addTextField { (field) in
dayOfWeekField = field
dayOfWeekField.placeholder = "dia de la semana"
dayOfWeekField.autocapitalizationType = .none
}
alert.addTextField { (field2) in
inicioTextField = field2
inicioTextField.placeholder = "Inicio Bloque (HH:MM)"
inicioTextField.keyboardType = .numbersAndPunctuation
}
alert.addTextField { (field3) in
terminoTextField = field3
terminoTextField.placeholder = "Término Bloque (HH:MM)"
terminoTextField.keyboardType = .numbersAndPunctuation
}
alert.addTextField { (field4) in
numeroDeCirugias = field4
numeroDeCirugias.placeholder = "Número Cirugías"
numeroDeCirugias.keyboardType = .numberPad
}
present(alert, animated: true, completion: nil)
}[enter image description here][1]
Try this solution. I suggest to not capture references to the UITextfields, maybe that might have caused the behavior. You can Access them by UIAlertController.textFields property. Usually all layouting is done by the UIAlertController basically fine, I never encountered bugs there.
Also. try to avoid force unwrapping with ! by using guard let
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "Agregar Nuevo Bloque", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Agregar", style: .default) { (_) in
let nuevoBloque = Bloques(context: self.context)
guard
let dayOfWeek = alert.textFields?[0].text,
let inicio = alert.textFields?[1].text,
let temino = alert.textFields?[2].text,
let numeroDeCirugiasString = alert.textFields?[3].text,
let numeroDeCirugias = Int(numeroDeCirugiasString)
else {
// not all textfields were implemented or filled out properly
return
}
nuevoBloque.dia = dayOfWeek
nuevoBloque.inicio = inicio
nuevoBloque.termino = termino
nuevoBloque.cirugias = numeroDeCirugias
self.bloques.append(nuevoBloque)
self.saveBloques()
}
alert.addAction(action)
alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
alert.addTextField { (field) in
field.placeholder = "dia de la semana"
field.autocapitalizationType = .none
}
alert.addTextField { (field2) in
field2.placeholder = "Inicio Bloque (HH:MM)"
field2.keyboardType = .numbersAndPunctuation
}
alert.addTextField { (field3) in
field3.placeholder = "Término Bloque (HH:MM)"
field3.keyboardType = .numbersAndPunctuation
}
alert.addTextField { (field4) in
field4.placeholder = "Número Cirugías"
field4.keyboardType = .numberPad
}
present(alert, animated: true, completion: nil)
}
EDIT:
Image of the Solution implemented by OP:

Get selected Day from UIDatePicker alert

Hi developers im trying to get the date & time from UIDatePicker
my UIDatePicker in on an alert
let myDatePicker: UIDatePicker = UIDatePicker()
let loc = Locale(identifier: "Es_mx")
//myDatePicker.timeZone = NSTimeZone.local
myDatePicker.locale = loc
let date = myDatePicker.date
let components = Calendar.current.dateComponents([.hour, .minute, .year, .day, .month], from: date)
let year = components.year!
let day = components.day!
let month = components.month!
let hour = components.hour!
let minute = components.minute!
myDatePicker.frame = CGRect(x: 0, y: 15, width: 270, height: 200)
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.alert)
alertController.view.addSubview(myDatePicker)
//let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default) { (somethingAction: UIAlertAction!) in
print("dia: \(day), mes: \(month), año: \(year), hora: \(hour), minuto: \(minute)")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)
alertController.addAction(somethingAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion:{})
}
already try
let date = myDatePicker.date
let components = Calendar.current.dateComponents([.hour, .minute, .year, .day, .month], from: date)
let year = components.year!
let day = components.day!
let month = components.month!
let hour = components.hour!
let minute = components.minute!
so when the user press OK button it prints:
print("dia: \(day), mes: \(month), año: \(year), hora: \(hour), minuto: \(minute)")
Print shows current day, month, year, hour and minute
im expect to get what the user selected from UIDatePicker
You initialize a datePicker and get the date from it immediately. This is the problem.
If you want to get the date from the datePicker at the time OK button pressed, you must do this in your closure. Move let date = myDatePicker.date line into your closure, Like so:
let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default) { (somethingAction: UIAlertAction!) in
let date = self.myDatePicker.date
print("dia: \(day), mes: \(month), año: \(year), hora: \(hour), minuto: \(minute)")
}

Set Time Default in UIDatePicker

I'm trying to populate a pickerView with a default value (String). Currently I'm able to capture it's value as a time after the user interacts with it, however I'm not able to set the time value before it becomes visible to the user.
I've tried
let test = dateFormatter.date(from: "09:00 AM")
timePicker.setDate(test, animated: false)
however that errors "Value of type '(UIDatePicker) -> ()' has no member 'setDate'"
#IBOutlet weak var timePicker: UIDatePicker!
#IBAction func timePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
//my attempt at passing in a string
let test = dateFormatter.date(from: "09:00 AM")
timePicker.setDate(test, animated: false)
tempTime = (dateFormatter.string(from: sender.date))//successfully captures the user's input value
}
Here's the function that launches the xib (containing the timePicker)
func showSomeDialogue() {
let newVC = SomeViewContoller(nibName: "SomeViewController", bundle: nil)
let popup = PopupDialog(viewController: newVC,
buttonAlignment: .horizontal,
transitionStyle: .bounceUp,
tapGestureDismissal: true,
panGestureDismissal: false)
present(popup, animated: true, completion: nil)
newVC.someDelegate = self as SomeDelegate
}
The xib's class
import UIKit
protocol MealDelegate {
func didCreateMeal(mealTime: String)
}
class SomeViewContoller: UIViewController {
var someDelegate: SomeDelegate!
var tempTime = ""
#IBOutlet weak var timePicker: UIDatePicker!
#IBAction func timePicker(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
tempTime = (dateFormatter.string(from: sender.date))
}
#IBAction func someSaveBtn(_ sender: UIButton) {
mealDelegate.didCreateMeal(mealTime: tempTime)
self.dismiss(animated: true, completion: nil)
}
}
Add following to your view controller class:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.date(from: "09:00 AM")
timePicker.date = date
Add the following to your SomeViewController class:
//MARK: - View Did Load
override func viewDidLoad() {
super.viewDidLoad()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.date(from: "10:57 PM")
//or whatever date you want to display as default
timePicker.setDate(date, animated: true)
}
Try this,
#IBAction func timePicker(_ sender: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .dateAndTime
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleTimePicker(sender:)), for: .valueChanged)
}
#objc func handleTimePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm "
tempTime = dateFormatter.string(from: sender.date)
// view.endEditing(true)
}

not printing selected dates to lable in swift

HI guys I have a date picker calculation app and Im wondering why the selected dates are not prtinting to my text lable. This is the code I have
#IBAction func calculateDays(sender: UIButton) {
if startDateTextField.text == "" || endDateTextField == "" {
let alert2 = UIAlertController(title: "Oops!", message: "Please Select a Start Date!", preferredStyle: UIAlertControllerStyle.Alert)
alert2.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert2, animated: true, completion: nil)
}
else {
let start = String(startDateTextField.text)
let end = String(endDateTextField.text)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
guard let startDate = dateFormatter.dateFromString(start), endDate = dateFormatter.dateFromString(end) else {
// You don't have dates, show error(print("error"), do no nothing - your choice.
return
}
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
let secondNewString = "\(components.day) days"
resultNumberOfDays.text = secondNewString
}
}
If I force unwrap as a test it works using (obviously this isn't safe)
let startDate:NSDate = dateFormatter.dateFromString(start)!
let endDate:NSDate = dateFormatter.dateFromString(end)!
any ideas on how to get the calculated dates to appear or letting me know what I'm missing here
thanks