我试图通过按主视图控制器中的按钮,将JSON值传输到另一个视图控制器中的标签。我的第一个视图控制器被称为“ ViewController”,第二个被称为“ AdvancedViewController”。下面的代码显示了如何获取JSON数据,并且工作正常,在MainViewController的标签中显示JSON值,但是当我将JSON值发送到AdvancedViewController的标签时,按下按钮,它将加载AdvancedViewController但标签值未更改?我已经在AdvancedViewController中分配了标签,但不确定为什么它不起作用。我正在尝试将其转移到高级视图控制器中的值“ avc.Label”
主要标签代码显示了如何在MainViewController中使其工作
代码如下:
我的主要ViewController:
guard let APIUrl = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=" + text + "&appid=e7b2054dc37b1f464d912c00dd309595&units=Metric") else { return }
//API KEY
URLSession.shared.dataTask(with: APIUrl) { data, response, error in
guard let data = data else { return }
let decoder = JSONDecoder()
//Decoder
do {
let weatherData = try decoder.decode(MyWeather.self, from: data)
if (self.MainLabel != nil)
{
if let gmain = (weatherData.weather?.first?.main) { //using .first because Weather is stored in an array
print(gmain)
DispatchQueue.main.async {
self.MainLabel.text! = String (gmain)
}
}
}
let avc = AdvancedViewController(nibName: "AdvancedViewController", bundle: nil)
if (avc.Label != nil)
{
if let mTest = (weatherData.weather?.first?.myDescription) { //using .first because Weather is stored in an array
DispatchQueue.main.async {
avc.Label.text! = String (mTest)
}
}
}
最佳答案
在AdvancedViewController中,创建存储mTest
值的变量
class AdvancedViewController: ViewController {
var test: String!
override func viewDidLoad(){
super.viewDidLoad()
if let test = test {
myLabel.text = test
}
}
}
let vc = storyboard?.instantiateViewController(withIdentifier: "AdvancedViewController") as! AdvancedViewController
if let mTest = (weatherData.weather?.first?.myDescription) {
vc.test = mTest
}
DispatchQueue.main.async {
present(vc, animated: true, completion: nil)
}