![](/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.