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

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

    In my case i have multiple sections and both the section and row index is vital, so in such a case i just created a property on UIButton which i set the cell indexPath like so:

    fileprivate struct AssociatedKeys {
        static var index = 0
    }
    
    extension UIButton {
    
        var indexPath: IndexPath? {
            get {
                return objc_getAssociatedObject(self, &AssociatedKeys.index) as? IndexPath
            }
            set {
                objc_setAssociatedObject(self, &AssociatedKeys.index, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
    

    Then set the property in cellForRowAt like this :

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
        cell.button.indexPath = indexPath
    }
    

    Then in the handleTapAction you can get the indexPath like this :

    @objc func handleTapAction(_ sender: UIButton) {
        self.selectedIndex = sender.indexPath
    
    }
    

提交回复
热议问题