Search code examples
iosswiftuitableviewviewwillappear

Dismissing Pushed view controller without NavigationController


I have two view controllers.

VC1 - Displays data in a tableView, selecting one of the cells goes to VC2. VC2 - Show text fields to edit the data.

Question - After updating the data and going back to VC1, it does not show the updated data in the table.

I did try adding tableView.reloadData() in ViewWIllAppear but the ViewWillAppear method is not called when I dismiss VC2.

//CODE BELOW VC2 -

@IBAction func saveTask(_ sender: Any) {
    self.dismiss(animated: true, completion: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)
    view.endEditing(true)
    if let task = task {
        task.completed = toggleStatus.isOn
    }
}

VC1 -

    override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    tableView.reloadData()
}

Solution

  • You have to update the item in the collection of your data that selected from table view

    Example:

    // The collection of your data is used to show in table view
    var data: [String] = []
    
    // After navigated back to the VC1, you have to update like:
    data[you_selected_index] = inputData // From VC2
    tableview.reloadData()
    
    

    UPDATED

    class VC1: UIViewController {
        private var selectedIndex: Int?
    
    }
    extension VC1: UITableViewDelegate {
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            selectedIndex = indexPath.row
            let vc = VC2()
            vc.delegate = self
            present(vc, animated: true, completion: nil)
        }
    }
    // MARK: - InputInfoVCDelegate
    extension VC1: VC2Delegate {
    
        func onInputInfoSuccessUpdated(source: String?) {
            // Updating data here
            guard let index = selectedIndex else { return }
            data[index] = source
            tableView.reloadData()
        }
    }
    
    protocol VC2Delegate: class {
        func onInputInfoSuccessUpdated(source: String?)
    }
    class VC2: UIViewController {
    
        weak var delegate: VC2Delegate?
    
        @IBAction private func actionTapToBackButton(_ sender: Any) {
            delegate?.onInputInfoSuccessUpdated(source: inputTextField.text)
        }
    }