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

前端 未结 19 2806
梦如初夏
梦如初夏 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:49

    Swift 4 and 5

    Method 1 using Protocol delegate

    For example, you have a UITableViewCell with name MyCell

    class MyCell: UITableViewCell {
        
        var delegate:MyCellDelegate!
        
        @IBAction private func myAction(_ sender: UIButton){
            delegate.didPressButton(cell: self)
        }
    }
    

    Now create a protocol

    protocol MyCellDelegate {
        func didPressButton(cell: UITableViewCell)
    }
    

    Next step, create an Extension of UITableView

    extension UITableView {
        func returnIndexPath(cell: UITableViewCell) -> IndexPath?{
            guard let indexPath = self.indexPath(for: cell) else {
                return nil
            }
            return indexPath
        }
    }
    

    In your UIViewController implement the protocol MyCellDelegate

    class ViewController: UIViewController, MyCellDelegate {
         
        func didPressButton(cell: UITableViewCell) {
            if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
                  print(indexpath)
            }
        }
    }
    

    Method 2 using closures

    In UIViewController

    override func viewDidLoad() {
            super.viewDidLoad()
           //using the same `UITableView extension` get the IndexPath here
            didPressButton = { cell in
                if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
                      print(indexpath)
                }
            }
        }
    
     var didPressButton: ((UITableViewCell) -> Void)
    
    class MyCell: UITableViewCell {
    
        @IBAction private func myAction(_ sender: UIButton){
            didPressButton(self)
        }
    }
    

    Note:- if you want to get UICollectionView indexPath you can use this UICollectionView extension and repeat the above steps

    extension UICollectionView {
        func returnIndexPath(cell: UICollectionViewCell) -> IndexPath?{
            guard let indexPath = self.indexPath(for: cell) else {
                return nil
            }
            return indexPath
        }
    }
    

提交回复
热议问题