I have some data coming from the API and I am showing them in tableView cells, Each of those cell's have a "Download" button, I need to assign a fileID from API to the cell that the user has selected to Download.
I have already set up the button to a UITableViewCell
class, I just need to have a idea how to make the button get the fileID depending on which cell is clicked since every cell has it's own fileID.
paymentsViewController
class:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "paymentsCell", for: indexPath) as? paymentsModel else {return UITableViewCell()}
let currentInvoice = payments.Result![changeCustomerKey.DefaultsKeys.keyTwo].properties?[0].payments
let currentInvoices = currentInvoice?[indexPath.row]
cell.priceLabelPayments?.text = "€\(currentInvoices?.amount ?? 0.00)"
cell.whenDateLabel?.text = "\(currentInvoices?.insertionDate?.convertToDisplayForm() ?? "")"
cell.fromSubLabel.text = "\(currentInvoices?.bank ?? "")"
cell.downloadButtonPayments.layer.cornerRadius = CGFloat(5)
cell.localizePaymentsModel()
return cell
}
}
paymentsModel
class:
class paymentsModel: UITableViewCell {
@IBOutlet weak var cellContentViewPayments: UIView!
@IBOutlet weak var downloadButtonPayments: UIButton!
@IBOutlet weak var priceLabelPayments: UILabel!
@IBOutlet weak var fromSubLabel: UILabel!
@IBOutlet weak var whenDateLabel: UILabel!
func localizePaymentsModel() {
let defaults = UserDefaults.standard
let lang = defaults.string(forKey: changeLanguageKey.DefaultsKeys.keyOne)
downloadButtonPayments.setTitle(NSLocalizedString("Download", tableName: nil, bundle: changeLanguage.createBundlePath(lang: lang ?? "sq" ), value: "", comment: ""), for: UIControl.State.normal)
}
}
CodePudding user response:
You are thinking about this wrong. It isn't the cell that has the fileID. When the user taps on a cell or a button, you should ask the table view (or collection view) for the indexPath it currently occupies, then use the IndexPath to look up the model data for that entry.
See my answer here:
Thant link shows code that lets you figure out the IndexPath for any view in a table view cell. You could use that code from your button's IBAction.