昨天我們已經能成功選擇天氣預報想查看的地點和時間了
App上的資訊也會隨著UIPickerView的選擇而做改變
但這樣看起來好像還有點不完美,所以我們打算增加天氣圖示以及讓背景圖片能根據目前天氣而改變,這樣能讓我們更了解現在的天氣狀況!
首先,我們先拉好兩個UIImageView並拉好@IBOutlet
接著將所需要用到的背景圖片放到Assets.xcassets裡面
至於天氣圖示是使用Xcode內建的圖片,如果不知道圖片名稱,可以到這裡搜尋看看
再來寫一個function來判斷Wx天氣現象的文字裡面是否有包含關鍵字讓天氣圖示與背景圖片做出相對應的改變
func changeWeatherImage() {
if wx.text!.contains("積冰") {
weatherImage.image = UIImage.init(systemName: "snow")
backgroundImage.image = UIImage(named: "snowground")
}
else if wx.text!.contains("暴風雪"){
weatherImage.image = UIImage.init(systemName: "wind.snow")
backgroundImage.image = UIImage(named: "brizzard")
}
else if wx.text!.contains("雪") {
if wx.text!.contains("雨") {
weatherImage.image = UIImage.init(systemName: "cloud.sleet")
backgroundImage.image = UIImage(named: "sleet")
}
else {
weatherImage.image = UIImage.init(systemName: "cloud.snow")
backgroundImage.image = UIImage(named: "snow")
}
}
else if wx.text!.contains("雨") {
if wx.text!.contains("雷") {
weatherImage.image = UIImage.init(systemName: "cloud.bolt.rain")
backgroundImage.image = UIImage(named: "thunder rain")
}
else if wx.text!.contains("晴"){
weatherImage.image = UIImage.init(systemName: "cloud.sun.rain")
backgroundImage.image = UIImage(named: "sun cloud rain")
}
else {
weatherImage.image = UIImage.init(systemName: "cloud.rain")
backgroundImage.image = UIImage(named: "rain")
}
}
else if wx.text!.contains("晴") {
if wx.text!.contains("雲") {
weatherImage.image = UIImage.init(systemName: "cloud.sun")
backgroundImage.image = UIImage(named: "cloud and sun")
}
else {
weatherImage.image = UIImage.init(systemName: "sun.max")
backgroundImage.image = UIImage(named: "sun")
}
}
else if wx.text!.contains("陰") {
weatherImage.image = UIImage.init(systemName: "smoke.fill")
backgroundImage.image = UIImage(named: "cloudy day")
}
else if wx.text!.contains("雲") {
weatherImage.image = UIImage.init(systemName: "smoke")
backgroundImage.image = UIImage(named: "cloud")
}
}
執行結果如下
如此一來我們的天氣App就完成啦!