I'm trying to update UILabel and UIImageView in main thread but its not working.
I have two ViewControllers(I'll call them ChooseCountryVC and DisplayCountryVC here) and in ChooseCountryVC, user can choose a country they like and in DisplayCountryVC I want to display the country's name in label and country's flag in imageView.
Basic process flow is below.
Code example related to this matter is below.
●ChooseCountryVC
// 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
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
}
}
}
If anybody knows whats wrong with my codes or need more information, please let me know.
// 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
Here you init a new view controller and set the value to it.
Your chosenCountryCode is set to the NEW view controller rather than your original DisplayCountryVC.
After your ChooseCountryVC dismissed, you go back to your original DisplayCountryVC. This new DisplayCountryVC is NOT presented or used.
You need to write a delegate or a callback to pass the chosen country code to your original DisplayCountryVC.