UITableViewCell Buttons with action

前端 未结 7 945
无人共我
无人共我 2020-12-01 00:27

Hi I have a custom UITableViewCell with three buttons to handle a shopping cart function, Plus,Minus and Delete button and I need to know which cell has been touched.

相关标签:
7条回答
  • 2020-12-01 01:13

    @pedrouan is great, except using button's tag option. In many cases, when you set button on tableViewCell, those buttons will modify tableView dataSource.(e.g. InsertRow, DeleteRow).

    But the tag of the button is not updated even if a new cell is inserted or deleted. Therefore, it is better to pass the cell itself as a parameter rather than passing the button's tag to the parameter.

    Here is my example to achieve this.

    Your ExampleCell

    protocol ExampleCellDelegate: class {
        func didTapButton(cell: ExampleCell)
    }
    
    class ExampleCell: UITableViewCell {
    
        weak var cellDelegate: ExampleCellDelegate?
    
        @IBAction func btnTapped(_ sender: UIButton) {
            cellDelegate?.didTapButton(cell: self)
        }
    }
    

    Your ViewController

    class ViewController: ExampleCellDelegate {
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            if let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell", for: indexPath) as? ExampleCell {
    
                cell.cellDelegate = self
                return cell
            }
            return UITableViewCell()
        }
    
        func didTapButton(cell: ExampleCell) {
            if let indexPath = tableView.indexPath(for: cell) {
                // do Something
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题