I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped. This is what I currently have, but it always is 0
var point =
// CustomCell.swift
protocol CustomCellDelegate {
func tapDeleteButton(at cell: CustomCell)
}
class CustomCell: UICollectionViewCell {
var delegate: CustomCellDelegate?
fileprivate let deleteButton: UIButton = {
let button = UIButton(frame: .zero)
button.setImage(UIImage(named: "delete"), for: .normal)
button.addTarget(self, action: #selector(deleteButtonTapped(_:)), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
@objc fileprivate func deleteButtonTapped(_sender: UIButton) {
delegate?.tapDeleteButton(at: self)
}
}
// ViewController.swift
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as? CustomCell else {
fatalError("Unexpected cell instead of CustomCell")
}
cell.delegate = self
return cell
}
}
extension ViewController: CustomCellDelegate {
func tapDeleteButton(at cell: CustomCell) {
// Here we get the indexPath of the cell what we tapped on.
let indexPath = collectionView.indexPath(for: cell)
}
}