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

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

    Sometimes button may be inside of another view of UITableViewCell. In that case superview.superview may not give the cell object and hence the indexPath will be nil.

    In that case we should keep finding the superview until we get the cell object.

    Function to get cell object by superview

    func getCellForView(view:UIView) -> UITableViewCell?
    {
        var superView = view.superview
    
        while superView != nil
        {
            if superView is UITableViewCell
            {
                return superView as? UITableViewCell
            }
            else
            {
                superView = superView?.superview
            }
        }
    
        return nil
    }
    

    Now we can get indexPath on button tap as below

    @IBAction func tapButton(_ sender: UIButton)
    {
        let cell = getCellForView(view: sender)
        let indexPath = myTabelView.indexPath(for: cell)
    }
    

提交回复
热议问题