This question has been asked a couple of times in lots of places, but it is extremely difficult to understand and solve it.
My problem is different, and I am asking this question after researching for more than 5 hours.
I have a tableView where I have 3 different types of CustomCells.
My custom cells have 3 things, 2 common a Label and a TextField. 3rd item (stepper, button, switch)
I have dynamically placed 10 cells calling
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
What I want to do ideally ->
When my users change the data on the cells, I would like to get all the 'updated' data so I can save it to my database when I click 'Save'.
I tried using
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
and using breakpoints, apparently the codeblock gets triggered when I touch the cell. Unfortunately, touch means literally touching the list entry body.
if I use the UI items (stepper/switch) which are within my custom cell, this code portion does not get triggered.
I have seen solutions using Tags and Delegates, but since I am new to iOS, I am not sure how to implement or go ahead. I am using Angela's Udemy iOS course to teach myself.
Custom Cell
Overall screen, I like to get the textfield values, when user changes them
(Tested) Hello, one way in which I used to solve this was to add the handler function outside of the subclass inside where you have initialized your tableView.
//.... This is your cellForRowAt tableView function..
let cell = self.tableView.dequeueReusableCell(withIdentifier: cellId) as! cellSubclass
cell.stepperButton.addTarget(self, action: #selector(handleStep(_:)), for: .valueChanged)
return cell
}
@objc func handleStep(_ sender: UIStepper) {
print(sender.value)
let indexPath : IndexPath = IndexPath(item: 0, section: 0)
// Put the correct item # to locate where you have the stepper,
// Then create a separate function doing the same thing, but with the item
// number of the next cell where you get the value from the switch
let cell = tableView.cellForRow(at: indexPath) as! cellSubclass
cell.textField.text = "\(Int(sender.value))"
}
You are connecting the UIStepper through the addTarget method inside of the function where you are creating your cells.
Here is a picture of my result:
Tip: add stepper.minimumValue = 0
This disables the [ - ] button when the value == 0.