Search code examples
iosswiftswift4

Send data from TableView (present modally) to ViewController inside textfield


In my HomeViewController I have a text field and a button. User can write a city or touch in this button to find a city. When button is touched, a CitiesTableView shows up by segue (present modally). When choose a city of the table list, I want to send this selected city to inside the text field in HomeViewController.


class HomeViewController: UIViewController{

    @IBOutlet weak var tfSearchCity: UITextField!
   //Button with Segue to present Modally CitiesTableViewController
    
    var cities = [Cities]()   
}
// Protocol to receive data
extension HomeViewController: CitieFinderDelegate{
    func addCity(city: Cities){
            tfSearchCity.text = city.City
            print(city)
        }
    }
}

I create a Protocol to pass data between views but is not working.


protocol CitieFinderDelegate {
    func addCity(city: Cities)
}
// this TableView are presenting Modally
class CitiesTableViewController: UITableViewController {

    var cities: [Cities] = []
    var delegate: CitieFinderDelegate?

    override func viewDidLoad() {
        super.viewDidLoad() 

    }
    // MARK: - Table view data source

     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let city = cities[indexPath.row]

        let findCity = Cities(UF: city.UF, City: city.City)
        delegate?.addCity(city: findCity)
  }
   
 // MARK: - Action to close the view
    
    @IBAction func close(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
    }}


Solution

  • It seems that the delegate hasn't been assigned to HomeViewController's instance. Make sure you have the below code in your HomeViewController

    override func prepare(for segue: UIStoryboardSegue, sender _: Any?) {
        if segue.identifier == "segue identifier name",
            let citiesViewController = segue.destination as? CitiesTableViewController {
            // cities assigned
            citiesViewController.delegate = self
        }
    }