Swift 4.2 Delete data TableViewCell use Button "(_ sender: UIButton)"


Using tags to track index paths is a common but very poor practice. It fails in any table view that allows rows to be deleted, inserted, or moved because remaining cells now have invalid tags unless the table view is fully reloaded using reloadData.






 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ATableViewCell
        cell.deleteButton.addTarget(self, action: #selector(nHapusTap(_:)), for: .touchUpInside)            

        return cell
    }

  @objc func nHapusTap(_ sender: UIButton) {
        let hitPoint = sender.convert(CGPoint.zero, to: tableView)
        if let indexPath = tableView.indexPathForRow(at: hitPoint) {

            self.dataArray.remove(at: indexPath.row)
            tableView.beginUpdates()
            tableView.deleteRows(at: [indexPath], with: .automatic)
            tableView.endUpdates()

        }

    }








No comments: