Search code examples
iosswiftuitableviewswift3uidatepicker

How to Display data from a UIDatePicker into a UITableView?


I would like to get the date from a UIDatePicker and add it to a UITableView cell. enter image description here

I have tried to put a label into a Table View Cell and update each time the person using the app clicks add date. However, it is the un-logical way to do it, and Xcode does not let me do it by giving me errors.

I have therefore put a label outside the tableview to just test and whenever I click on the Add Date button, the date gets displayed.

Here is my code from the view controller folder

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var examDatePicker: UIDatePicker!

@IBOutlet weak var AddClassButton: UIButton!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var datesTable: UITableViewCell!

override func viewDidLoad() {

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    AddClassButton.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside)


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func pressButton(button: UIButton) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MMM yyyy"
    let selectedDate = dateFormatter.string(from: examDatePicker.date)


    dateLabel.text = selectedDate

  //  datesTable

    //myDatePicker.datePickerMode = UIDatePickerMode.Date
        }



  }

Solution

  • You need to implement data source method of table view and after select date from datepicker you need to reload tableview and assign that selected date to cell's label

    class ViewController: UIViewController {
    
     var selectedDate : String ? //Make global variable 
    
     func pressButton(button: UIButton) {
         let dateFormatter = DateFormatter()
         dateFormatter.dateFormat = "dd MMM yyyy"
         selectedDate = dateFormatter.string(from: examDatePicker.date)
         self.IBtableView.reload()
     }
    
    
     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
          return 1 //anything you want
     }
    
      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    
       let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? YourCustomCell // Or UITableViewCell
       cell. dateLabel.text = selectedDate ?? "SelectDateFromDatePicker"
      }
    }