So I am creating an alarm clock. One view controller is a table view. The other view controller consists of a UIDatePicker with a submit button. The goal is that when the user clicks the submit button, it saves the date on the date picker. As well as saving the date, it is a segue to the table view controller. I am trying to display the time saved as the label in the cell.
This is my code for the DatePicker view controller. I defined the variable outside of the function. Then when they click submit it should update the value. However it does not update it when it passes through the segue.
var myDate = "1:39 PM"
@IBAction func submitDate(_ sender: AnyObject) {
myDate = DateFormatter.localizedString(from: dateOutlet.date, dateStyle: DateFormatter.Style.none, timeStyle: DateFormatter.Style.short)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "save" {
let toViewController = segue.destination as! TableViewController
toViewController.myDate = myDate
}
}
This is my code for the table view controller. When i click submit, it does not show the label as the time chosen in the DatePicker. It shows "1: 39 PM." Which was what I initially defined it as.
var myDate = "0"
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell
cell.textLabel?.text = myDate
return cell
}
Don't bother trying to declare myDate
in your source view controller unless you are going to use it later.
Also, if you didn't have any code in your submitDate
function to present your target view controller, you probably don't need it as your 'save'
segue you set takes care of that automatically.
In source view controller
@IBAction func submitDate(_ sender: AnyObject) {
//don't need anything here - remove this function unless doing anything else
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "save" {
if let toViewController = segue.destination as? TableViewController {
toViewController.myDate = DateFormatter.localizedString(from: dateOutlet.date, dateStyle: DateFormatter.Style.none, timeStyle: DateFormatter.Style.short)
}
}
}
In target view controller
var myDate: String!
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell
cell.textLabel?.text = myDate
return cell
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With