Home > Software engineering >  How to remove a cell from a TableView from another ViewController when tap on UIButton (Swift)
How to remove a cell from a TableView from another ViewController when tap on UIButton (Swift)

Time:09-27

There are 2 ViewController's. On the first ViewController one there is a table with cells. When you click on a cell, a second ViewController opens, on which information from the cell is located and a button, when press, the cell should be deleted and a return to the first ViewController should occur.

I get indexForCell in the cellForRowAt method

  var data: [String] = []
  var indexForCell: Int?

    private func configData() {
        service.addMessage(offset: offsetStart) { [weak self] result in
            switch result {
            case .success(let dataMessage):
                self?.data = dataMessage
                DispatchQueue.main.async {
                    self?.messageTable.reloadData()
                }
            case.failure(let error):
                print(error)
                DispatchQueue.main.async {
                    self?.showAlert(title: "Error", message: "Error connecting to the server")
                }
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let textMessage = data[indexPath.row]
        let infoController = InfoController()
        
        
        infoController.messageLabel.text = textMessage
        indexForCell = indexPath.row
        navigationController?.pushViewController(infoController, animated: true)
    }

But when I access my indexForCell from the second ViewController, I understand that my data is empty and the indexForCell = nil

let startController = StartController()
private let deleteButton = CustomButton()

    @objc private func tapDeleteButton() {
        
       //delete cell from 1st ViewController
        startController.messageTable.reloadData()
        navigationController?.popViewController(animated: true)
    }

What do I need to add to func tapDeleteButton() to successfully delete a cell?

Thank you so much in advance!

CodePudding user response:

Inside InfoController add this property

 weak var delegate:StartController?

Then set it here

 let infoController = InfoController()
 infoController.delegate = self

Finally you can use it to delete

delegate?.deleteItem()
navigationController?.popViewController(animated: true)

And create deleteItem method inside StartController to do the process using indexForCell that you set before

  • Related