将数据从 TableView(以模态方式呈现)发送到文本字段内的 ViewController

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

在我的 HomeViewController 中,我有一个文本字段和一个按钮。用户可以写一个城市或触摸这个按钮来查找一个城市。触摸按钮时,CitiesTableView 会按顺序显示(模态显示)。 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)
        }
    }
}

我创建了一个在视图之间传递数据的协议,但它不起作用。


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)
    }
    }}

委托似乎还没有分配给 HomeViewController 的实例。 确保您的 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
    }
}