How to get the indexpath.row when an element is activated?

前端 未结 19 2169
梦如初夏
梦如初夏 2020-11-21 23:30

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 =         


        
19条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 23:52

    // 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)
        }
    
    }
    

提交回复
热议问题