为什么自委托是零?

Why self delegate is nil?

我想通过使用 openweathermap 添加城市名称来制作一个天气应用程序 api。但是我无法将我在 AddCityViewController 中添加的城市发送回 HomeViewController。因为,self?.delegate 是 nil,在 AddCityViewController.swift

 @objc private func didTapSaveButton() {
    print("clicked save button")
    
    if let city = cityTextfield.text {
        
        let weatherURL = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(city)&APPID=b4251cb51691654da529bccf471596bc&units=imperial")!
        
        let weatherResource = Resource<WeatherViewModel>(url: weatherURL) { data in
            
            let weatherVM = try? JSONDecoder().decode(WeatherViewModel.self, from: data)        
            return weatherVM
        }
        
        Webservice().load(resource: weatherResource) { [weak self] result in
            if let weatherVM = result {
                
                if let delegate = self?.delegate {
                    delegate.addWeatherDidSave(vm: weatherVM)
                    self?.dismiss(animated: true, completion: nil)
                }
            }
        }
    }
}

当我调试时 HomeViewController.swift 中的准备函数没有被调用。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
    guard let nav = segue.destination as? UINavigationController else {
        fatalError("NavigationController not found")
    }
    
    guard let addWeatherCityVC = nav.viewControllers.first as? AddCityViewController else {
        fatalError("AddWeatherCityController not found")
    }
    
    addWeatherCityVC.delegate = self
    
}

我想要的是,当用户按下保存按钮时,我想将城市名称传递回 HomeViewController。

extension HomeViewController: AddWeatherDelegate {
   func addWeatherDidSave(vm: WeatherViewModel) {
      print(vm.name)
   }  
}

Source code in GitHub

您没有使用 segue 进行导航,因此不会触发 prepareForSegue 方法。在您的代码中,您正在手动初始化 AddCityViewController 的实例并呈现它。因此,要解决此问题,您必须将委托设置为该实例。

@objc private func didTapAddButton() {
   let vc = AddCityViewController()
   vc.title = "Add City"
   vc.delegate = self
   let nav = UINavigationController(rootViewController: vc)
   nav.modalPresentationStyle = .fullScreen
   present(nav, animated: true)
 }

否则您可以使用 segue 进行导航。