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

前端 未结 19 2316
梦如初夏
梦如初夏 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-22 00:06

    After seeing Paulw11's suggestion of using a delegate callback, I wanted to elaborate on it slightly/put forward another, similar suggestion. Should you not want to use the delegate pattern you can utilise closures in swift as follows:

    Your cell class:

    class Cell: UITableViewCell {
        @IBOutlet var button: UIButton!
    
        var buttonAction: ((sender: AnyObject) -> Void)?
    
        @IBAction func buttonPressed(sender: AnyObject) {
            self.buttonAction?(sender)
        }
    }
    

    Your cellForRowAtIndexPath method:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
        cell.buttonAction = { (sender) in
            // Do whatever you want from your button here.
        }
        // OR
        cell.buttonAction = buttonPressed // <- Method on the view controller to handle button presses.
    }
    

提交回复
热议问题