无法使用 didSet swift 更新主线程中的 UI



我正在尝试在主线程中更新UILabel和UIImageView,但它不起作用。

我有两个ViewControllers(我在这里称它们为ChooseCountryVC和DisplayCountryVC(,在ChooseCountryVC中,用户可以选择他们喜欢的国家,在DisplayCountryVC中,我想在标签中显示国家名称,在imageView中显示国家国旗。

基本工艺流程如下。

  1. 点击"选择一个国家"按钮在显示国家VC
  2. 目前选择国家VC,它基本上是所有国家的表格视图,用户可以选择一个国家
  3. 当用户选择国家/地区时,在 DisplayCountryVC 中设置名为"countryCode"的属性,并关闭 ChooseCountryVC 以返回到 DisplayCountryVC
  4. 在 DisplayCountryVC 中 "countryCode" 上的 didSet 函数中,将 UI 更新过程添加到主线程。

与此相关的代码示例如下。

●选择国家VC

// when user has chosen a country and dismiss this VC
let displayCountryVC = DisplayCountryVC()
displayCountryVC.countryCode = self.chosenCountryCode
self.dismiss(animated: true, completion: nil) // go back to DisplayCountryVC

●显示国VC

var countryCode: String? {
didSet {
guard let countryCode = countryCode else {return}
let countryName = self.getCountryName(with: countryCode) // this function provides countryName with no problem
let flagImage = self.getFlag(with: countryCode) // this function provides flag image with no problem
DispatchQueue.main.async {
self.imageView.image = flagImage 
self.label.text = countryName
print("label's text is", self.label.text) // somehow, this prints out country's name correctly in console but apparently UI has not been updated at all
}
}
}

如果有人知道我的代码出了什么问题或需要更多信息,请告诉我。

// when user has chosen a country and dismiss this VC
let displayCountryVC = DisplayCountryVC()
displayCountryVC.countryCode = self.chosenCountryCode
self.dismiss(animated: true, completion: nil) // go back to DisplayCountryVC

在这里,您初始化一个新的视图控制器并为其设置值。

您选择的国家/地区代码设置为新的视图控制器,而不是原始的 DisplayCountryVC。

在您的 ChooseCountryVC 被关闭后,您将返回到原来的 DisplayCountryVC。这个新的DisplayCountryVC没有被呈现或使用。

您需要编写一个委托或回调,将所选国家/地区代码传递给您的原始 DisplayCountryVC。

最新更新