eberhapa
eberhapa

Reputation: 368

Swift: How to iterate through all tableViewRows on button press

I have created a static tableView and want to save the data from each tableViewCell (all cells are different custom tableViewCells) to CoreData. How do I iterate through all TableViewCells on button press? I'm not using Storyboard so i do not have IBOutlets.

EDIT: Sorry, maybe i should specify my problem. See the code below. I have 3 CustomCells. FirstCustomCell includes a Textfield, SecondCustomCell a UIPickerView and ThirdCustomCell a UIDatePicker. The controller also includes a saveButton(). If i press the button i want to get the inputs from the TextField, UIPickerView and UIDatePicker.

//TableViewController
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
    case 0:
        return tableView.dequeueReusableCell(withIdentifier: cellId1) as! FirstCustomCell //includes a UITextField
    case 1:
        return tableView.dequeueReusableCell(withIdentifier: cellId2) as! SecondCustomCell //includes a UIPickerView
    case 2:
        return tableView.dequeueReusableCell(withIdentifier: cellId3) as! ThirdCustomCell //includes a UIDatePicker
    default:
        return UITableViewCell(style: .default, reuseIdentifier: nil)
    }
}    

How can i access the input from the TextField, UIPickerView and UIDatePicker on saveButton() in my TableViewController?

Upvotes: 0

Views: 428

Answers (2)

The Mach System
The Mach System

Reputation: 6973

Short answer: You DON'T iterate through all table view rows. Here is the reason:

  • It is a STATIC table view. This means you created all table view cells programmatically (because you don't use storyboard). This means you know exactly how many cells there are.

What you should do:

  • Declare properties whenever you have a STATIC table view.
  • If each table view cell has the UITextField/UILabel/UISwitch/UIButton... that holds the data you need, declare a UITextField/UILabel/UISwitch/UIButton... property and access its data to save to core data.

Upvotes: 1

Duncan C
Duncan C

Reputation: 131491

You should not be storing data in your cells. You should have a model object that holds the data from the cells, and install your data into the cells. Then if the user edits that data you should be collecting the edits as they are made and applying them to your model.

Then you can persist your model to Core data cleanly and easily.

Right now you're using a static table view so you might be able to get away with the approach you are using, but that's not to say it is a good way to do it - it is most definitely NOT.

For a normal table view, there are more cells than will fit on the screen, and the table view recycles cells and reuses them as the user scrolls through them. When a cell scrolls off the screen, the settings in its fields get discarded.

Upvotes: 3

Related Questions