Search code examples
iosswifttableviewselectordelete-row

My selector is not calling the function in swift. Deleting tableViewCell programatically in iOS, swift 5


I have a method to delet a row in a tableview:

@objc func didTapDelete(_ sender: UIButton) {
    let point = sender.convert(CGPoint.zero, to: tableView)
    guard let indexPath = tableView.indexPathForRow(at: point) else {
        return
    }
    prescriptions.remove(at: indexPath.row)
    tableView.beginUpdates()
    tableView.deleteRows(at: [IndexPath(row: indexPath.row, section: 0)], with: .left)
    tableView.endUpdates()
}

In my cellForRowAt, im calling the button.addTarget i declared in the Customcell

        cell.deleteButton.addTarget(self, action: #selector(didTapDelete(_:)), for: .touchUpInside)

Here is the Button in the customCell

    let deleteButton: UIButton = {
    let variable = UIButton()
    variable.setTitle("Delete_Button".localized, for: .normal)
    variable.setTitleColor(Colors.red, for: .normal)
    variable.titleLabel?.font = UIFont.boldSystemFont(ofSize: Metrics.Spacing.medium)
    variable.translatesAutoresizingMaskIntoConstraints = false
    return variable
}()

The method is in the View inside the viewController, but when I click on the button, even though the debugger stops at the selector.addTarget call, my didTapDelete method is not called.

Im using swift 5, viewCode.

picture of the screen


Solution

  • I managed to resolve with

    cell.contentView.isUserInteractionEnabled = false
    

    The problem was because the tap its recognizing the cell click did select, not the button.