【问题标题】:Can't pass data between View Controller and Model无法在 View Controller 和 Model 之间传递数据
【发布时间】:2022-01-23 05:08:02
【问题描述】:

在我的视图控制器中有带有文本字段的 UIAlertController。当用户输入城市名称时,这个数据必须传输给模型,当我得到这个城市的坐标时。但我不能将城市名称从视图控制器传递给模型

我的 UIAlertController:

class MainScrenenViewController: UIViewController {
    
    var delegate: ILocationGroup?

    @objc func locationButtonTap() {
        let alert = UIAlertController(title: "Add city", message: nil, preferredStyle: .alert)
        let addButton = UIAlertAction(title: "Add", style: .default) { action in
           
            self.delegate?.addLocation(alert.textFields?.first?.text ?? "No City")
            
        }
        
        alert.addAction(addButton)
        let cancelButton = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        alert.addAction(cancelButton)
        
        alert.addTextField { textField in
            textField.placeholder = "Your City"
        }
        
        present(alert, animated: true, completion: nil)
    }

我的模特:

protocol ILocationGroup {
    
    func addLocation(_ name: String)
    
}

class LocationGroup: ILocationGroup {
    
    var mainScreenViewController: MainScrenenViewController?
        
    func addLocation(_ name: String) {
        
        mainScreenViewController?.delegate = self
        
                let url = "https://geocode-maps.yandex.ru/1.x/?apikey=fd93783b-fe25-4428-8c3b-38b155941c8c&format=json&geocode=\(name)"
                
                guard let url = URL(string: url) else { return }
                
                let task = URLSession.shared.dataTask(with: url) { data, response, error in
                    guard let data = data, error == nil else { return }
            
                    do {
                        let result = try JSONDecoder().decode(LocationData.self, from: data)
            
                        
                        print(result.response.geoObjectCollection.metaDataProperty.geocoderResponseMetaData.boundedBy.envelope.lowerCorner)
                    }
                    catch {
                        print("failed to convert \(error)")
                    }
            
                }
                task.resume()
    }
}

【问题讨论】:

  • 您必须在某处设置对mainScreenViewController 的引用。目前还不清楚这两个类是如何相关的。
  • 你还需要在VC中设置委托。目前尚不清楚这是否在显示之前被注入到 VC 中。最后,您将 json 解码为 dataTask 完成块中的局部变量,但随后不对其执行任何操作(除了打印它),因此即使您确实设法将城市数据放入 URLSession,结果位置值也会丢失当关闭完成时。

标签: swift xcode uialertcontroller


【解决方案1】:

我认为它应该是 var delegate: LocationGroup()

另外,我不会称它为委托,因为注册委托是 swift 中的关键字

https://manasaprema04.medium.com/different-ways-to-pass-data-between-viewcontrollers-views-8b7095e9b1bf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多