Gulz
Gulz

Reputation: 1813

pass data from custom cell(in table which is on ViewController) to the viewcontroller itself Swift3 iOS

I have a ViewController. The ViewController has a TableView in it. The TableView has a few custom cells (say one is with the DatePicker, second is TextField, third is whatever it is - that's not the case) - cells are described in a TableViewCell

So, I'm pressing the one with DatePicker, set the date "01.01.2016" on cell

ISSUE: I need to insert "01.01.2016" into a dictionary which is in the ViewController

would appreciate any advice thanks

Upvotes: 0

Views: 325

Answers (2)

dirtydanee
dirtydanee

Reputation: 6151

Create internal variables on your viewController:

class ViewController: UIViewController {
    // Keeping an internal reference to your datePicker
    internal var datePicker: UIDatePicker?
    // Keeping an internal reference to the indexPath, where you have the datepicker
    internal var datePickerIndexPath: IndexPath?
    // Your dictionary, where you want to save the date
    internal var dictionary: [String: Any] = [:]

Assign the datePicker and the indexPath in cellForRowAt, when you are dequeuing that cell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Dequeuing cells and some other logic

        // Assign the cell's datePicker to the internal datePicker
        self.datePicker = cell.datePicker
        self.datePickerIndexPath = indexPath
}

And in the didSelectRowAt function, just use the internal variables and your dictionary

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let datePickerIndexPath = self.datePickerIndexPath, datePickerIndexPath == indexPath {
            dictionary["date"] = self.datePicker?.date
        }
}

Hope this helps!

Upvotes: 1

PeterB
PeterB

Reputation: 58

You could have a delegation method in the ViewController that the custom TableViewCells call when the date selection happens. The ViewController can assign itself as the cell's delegate in cellForRowAtIndexPath.

Upvotes: 0

Related Questions