UITableViewCell Buttons with action

前端 未结 7 962
无人共我
无人共我 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:07

    I came across the same problem after making the IBOutlets private as has been broadly suggested by the community.

    Here is my solution:

    < In your cell class >

    protocol YourCellDelegate: class {
        func didTapButton(_ sender: UIButton)
    }
    
    class YourCell: UITableViewCell {
    
        weak var delegate: YourCellDelegate?
    
        @IBAction func buttonTapped(_ sender: UIButton) {
            delegate?.didTapButton(sender)
        }
    }
    

    < In your ViewController >

    class ViewController: UIViewController, YourCellDelegate {
    
        func didTapButton(_ sender: UIButton) {
            if let indexPath = getCurrentCellIndexPath(sender) {
                item = items[indexPath.row]
            }
        }
    
        func getCurrentCellIndexPath(_ sender: UIButton) -> IndexPath? {
            let buttonPosition = sender.convert(CGPoint.zero, to: tableView)
            if let indexPath: IndexPath = tableView.indexPathForRow(at: buttonPosition) {
                return indexPath
            }
            return nil
        }
    }
    

提交回复
热议问题