How to access index path of button in a custom TableViewCell?

前端 未结 3 427
半阙折子戏
半阙折子戏 2020-12-21 08:04

I have created a custom TableViewCell and currently have a button placed in the cell. When the button is pressed, In the tableviewcell.swift file,

3条回答
  •  旧时难觅i
    2020-12-21 08:36

    You could subclass UIButton in your cell with a property for its row.

    class MyButton: UIButton {
        var row: Int?
    }
    

    Then when you set up your table view, in the cellForRowAtIndexPath method, you set the row property:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            // ...
            cell.button.row = indexPath.row
            // ...
        }
    

    This way when the action fires, you can get the correct row:

    @IBAction func employeeAtLunch(sender: MyButton) {
        if let row = sender.row {
            // access the row
        }
    }
    

提交回复
热议问题