Search code examples
swiftuitableviewuitextfieldcelluidatepicker

Change cell.textField.text with a datePicker


In my tableViewCell, I have a UITextField calling a UIDatePicker (code below).

My problem is : I don’t understand how to pass the date (from datePicker) in the cell.myTextField (because it appears only on the cellForRowAtIndexPath method). Anyone could help me please ?

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

          //......... 

          cell.myTextField.addTarget(self, action: "showDatePicker:", forControlEvents: UIControlEvents.EditingDidBegin)

         //......... 
    }

    func showDatePicker(sender: UITextField) {

            var datePickerView:UIDatePicker = UIDatePicker()
            datePickerView.datePickerMode = UIDatePickerMode.Date
            sender.inputView = datePickerView

            datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)

    }

    func datePickerValueChanged(sender:UIDatePicker) {

            var dateFormatter = NSDateFormatter()
            dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle
            dateFormatter.timeStyle = NSDateFormatterStyle.FullStyle

            //dateTextField.text = dateFormatter.stringFromDate(sender.date)
            //How to load my cell.myTextField.text with the sender.date ?

    }

Solution

  • There are several ways of do it what you want, you can combine the cellForRowAtIndexPath (it's not the same as you declare as part of your UITableViewDataSource).

    To use the above method you need to know the indexPath or at least the index of the row and for this you can use the indexPathForSelectedRow to get exactly the selected row an and then set the value you want like in the following way:

    func datePickerValueChanged(sender:UIDatePicker) {
    
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle
        dateFormatter.timeStyle = NSDateFormatterStyle.FullStyle
    
        var indexPath = self.tableView.indexPathForSelectedRow()
        var cell = self.tableView.cellForRowAtIndexPath(indexPath)
        cell.dateTextField.text = dateFormatter.stringFromDate(sender.date)
    }
    

    I hope this help you.