Reputation: 776
Hit a bit of a brick wall with this problem.
I have a TableView which of dynamic prototype. The TableView has 2 sections.
Section 1 loads a custom TableViewCell from a xib file. The cell contains a stepper and a label:
class quantityTableViewCell: UITableViewCell {
@IBOutlet weak var quantityLabel: UILabel!
@IBAction func quantityStepper(_ sender: UIStepper) {
quantityLabel.text = String(Int(sender.value))
}
}
Section 2 loads another custom TableViewCell which contains just a button:
class addToBasketTableViewCell: UITableViewCell {
@IBOutlet weak var submitButton: UIButton!
}
Now in my TableView class where both cells are being loaded in their own sections, I want to capture the current value of 'quantityLabel' inside the first section when I click the button in the second section and print the result to console.
For example, if I step the value to 5, when I hit the 'submitButton' it prints '5'.
I'm a bit unsure how to go about this, any guidance would be great. Below is a copy of the cells being loaded:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item: ItemPreBasketModel = cellItems[indexPath.row] as! ItemPreBasketModel
if indexPath.section == 0 {
let quantityCell = Bundle.main.loadNibNamed("quantityTableViewCell", owner: self, options: nil)?.first as! quantityTableViewCell
return quantityCell
} else if indexPath.section == 1 {
let addToBasketCell = Bundle.main.loadNibNamed("addToBasketTableViewCell", owner: self, options: nil)?.first as! addToBasketTableViewCell
return addToBasketCell
}
}
Upvotes: 1
Views: 1267
Reputation: 375
It should be something like this:
let path = IndexPath(item: 0, section: 0)
let cell = table.cellForRow(at: path) as? quantityTableViewCell
print(cell?.quantityLabel.text)
replace "table" with your table object.
Upvotes: 3
Reputation: 10199
You should never rely on a value from a cell, because cells might appear and disappear when the user scrolls the table view.
Instead, you should store the value of the stepper in a model, and when the user taps on the button, read the value from the model (and not from any cell).
So:
quantityStepper
is called, update the label and inform some delegate (e.g. the hosting view controller) that the value changed. Be aware:
quantityTableViewCell
addToBasketTableViewCell
is called, you should also inform the delegate about this. The delegate (your view controller) then will then work with the value that he got in 3. and do whatever has to be done.With this approch, the cells are decoupled from each other. You don't have any problems with cell reusage, and you can initialize the cells properly because the value is always stored in the model, and the cells only display it. Updates are always reflected to the model.
Upvotes: 1