#ios #swift #swift4
#iOS #swift #swift4
Вопрос:
В моем HomeViewController у меня есть текстовое поле и кнопка. Пользователь может ввести город или нажать на эту кнопку, чтобы найти город. При нажатии кнопки отображается CitiesTableView с помощью segue (присутствует модально). При выборе города из списка таблиц я хочу отправить этот выбранный город внутрь текстового поля в 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)
}
}}
Ответ №1:
Похоже, что делегат не был назначен экземпляру 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
}
}