我试图在按钮函数末尾调用函数“Checks”,以便“Checks”函数能够检查应用程序中标签的值,并根据该值更改背景颜色在 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
}
}
最佳答案
您的问题是您在错误的位置调用了 self.Checks()
。您在加载数据之前很久就调用它(对异步调用进行一些研究)。将其移至完成处理程序内部,您可以在其中设置标签的文本。
DispatchQueue.main.async {
self.MainLabel.text! = String (gmain)
self.Checks()
}
不相关,但标准做法是函数名称、变量名称和枚举大小写以小写字母开头。类、结构和枚举名称以大写字母开头。
关于ios - 必须按同一按钮两次才能调用函数 Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52672827/