Search code examples
iosswiftuitableviewuitextfielduialertview

How to append new string to array via UITextField located in one VC, to populate TableView located in another?


Why TableView doesn't shows the new string added? How to fix it?

In first VC:

 @IBAction func saveButtonPressed(_ sender: UIButton) {
    
    var textField = UITextField()
    
    let alert = UIAlertController(title: "Save current run", message: "", preferredStyle: .alert)
    
    let action = UIAlertAction(title: "Save", style: .default) { (action) in
   
        RunHistoryTableViewController().runArray.append(textField.text!)
        RunHistoryTableViewController().tableView.reloadData()
        
    }
    alert.addTextField { saveRunTextField in
        saveRunTextField.placeholder = "Name your run"
        textField = saveRunTextField
    }
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
    }

}

In second VC:

 var runArray = ["BMW M3 Run 1", "BMW M3 Run 2", "Renault Megane RS"]

    //MARK: TableView DataSource:
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return runArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "RunCell", for: indexPath)
        
        cell.textLabel?.text = runArray[indexPath.row]
        
        return cell
    }
}

Bear in mind I'm a beginner, could use some help as none of my ideas seemed to work.


Solution

  • I think you have two ways to achieve this:

    1- To use protocols and pass the data in this protocol

    2- To use segue and pass the data in this segue

    The most recommended solution in such a case is to use the protocol to get the result and to have a good performance.