我正在尝试在按钮功能的末尾调用功能“检查”,以便“检查”功能能够检查应用程序中标签的值,并根据该值更改背景色在GoButton函数中操作的标签。例如如果天气是“多云”,那么我将显示一些雨云,然后遮住阳光,然后遮雨。现在,当我按下按钮时,该按钮可以正常工作,但是没有调用Checks函数,然后我不得不再次按下相同的按钮才能调用它?
我尝试将self.Checks()行放置在catch上方和外部,但这没什么区别,我仍然必须按两次GoButton才能使其生效,并更改背景。
按钮功能:
//Go Button in Main View Controller
@IBAction func GoButton(_ sender: Any) {
//text IS EQUAL TO WHAT IS IN THE TEXT BOX
let text: String = userValue.text!
//API URL TO FETCH JSON DATA
guard let APIUrl = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=" + text + "&appid=***API***KEY***&units=Metric") else { return }
URLSession.shared.dataTask(with: APIUrl) { data, response, error in
guard let data = data else { return }
//JSON DECODER
let decoder = JSONDecoder()
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)
}
}
}
} catch {
print("Error in fetching data for your location: \(error)")
}
}.resume()
self.Checks()
}
检查功能:
func Checks() {
//For some reason, this function doesn't get called on the first time you press the button? <<<<<<<<<<<<<<<<<<<<<
if (MainLabel.text! == "Rain") {
rainClouds.isHidden = false
rain.isHidden = false
sun.isHidden = true
} else if (MainLabel.text! == "Drizzle") {
rainClouds.isHidden = false
rain.isHidden = false
sun.isHidden = true
} else if (MainLabel.text! == "Clouds") {
rainClouds.isHidden = false
rain.isHidden = true
sun.isHidden = true
} else if (MainLabel.text! == "Cloudy") {
rainClouds.isHidden = false
rain.isHidden = true
sun.isHidden = true
}
}
答案 0 :(得分:0)
您的函数中有两个位置,当防护条件失败时,它们会静默返回。我会在这些块中塞入日志语句,以查看是哪个原因导致它在您首次调用该函数时过早退出,然后您可以继续进行操作。
作为旁注,我还建议使用更具描述性的函数名称,以及不能与变量或对象名称混淆的函数名称。
答案 1 :(得分:0)
您的问题是您在错误的位置致电self.Checks()
。您要在加载数据之前调用它(对异步调用进行一些研究)。将其移至设置标签文本的完成处理程序内部。
DispatchQueue.main.async {
self.MainLabel.text! = String (gmain)
self.Checks()
}
不相关,但标准做法是函数名称,变量名称和枚举大小写以小写字母开头。类,结构和枚举名称以大写字母开头。