![](/img/trans.png)
[英]Navigate to another ViewController from Swift Controller to Objective C controller
[英]Update the viewController from the controller in MVC with SWIFT
我正在快速创建一个应用程序。 该应用程序从WeatherWeatherModel类的openweathermap.com api获取天气,然后在加载数据时,模型要求viewController更新数据
我正在使用Swift 5的Xcode 10.2.1
我已经在模型中创建了一个协议来更新数据,但是updateDisplayDelegate?.updateWeatherDataOnDisplay()始终为nil,即使我从控制台中的JSON获取数据,它也不会在屏幕上更新
class WeatherDataModel {
var updateDisplayDelegate: ProtocolUpdateDisplay?
func updateWeaterData(json : JSON) {
updateDisplayDelegate?.updateWeatherDataOnDisplay()
}
}
public protocol ProtocolUpdateDisplay {
func updateWeatherDataOnDisplay()
}
class MainViewController: UIViewController {
let weatherDataModel = WeatherDataModel()
override func viewDidLoad() {
super.viewDidLoad()
weatherDataModel.updateDisplayDelegate = self
}
extension MainViewController: ProtocolUpdateDisplay {
func updateWeatherDataOnDisplay() {
cityLabel.text = weatherDataModel.city
tempLabel.text = weatherDataModel.temperature
weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}
}
您不应将delegation
模式用于模型。 考虑使用通知:
func updateWeaterData(json : JSON) {
NotificationCenter.default.post(Notification(name: Notification.Name("WeatherDidUpdate")))
}
并在您要响应此通知的任何控制器中进行观察:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(updateWeatherDataOnDisplay(_:)), name: Notification.Name("WeatherDidUpdate"), object: nil)
}
@objc func updateWeatherDataOnDisplay(_ notification: Notification) {
cityLabel.text = weatherDataModel.city
tempLabel.text = weatherDataModel.temperature
weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}
并最后删除观察者:
deinit {
NotificationCenter.default.removeObserver(self)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.