简体   繁体   中英

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM