我想根据变量更改图像,我不确定如何做到这一点。
我认为我的代码是正确的,但是在iOS模拟器中,图像只是空白。我想知道为什么?
以下是我的代码:
import UIKit
class BuyTicketViewController:UIViewController {
@IBOutlet weak var stadiumImage: UIImageView!
@IBOutlet weak var logoImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
if (globalVenueSelected == "Gillingham Football Club"){
let imageGillinghmaFootballClub : UIImage = UIImage(named: "gillinghamStadium.jpg")!
let stadiumImage = (image: imageGillinghmaFootballClub)
}
if (globalVenueSelected == "Old Trafford"){
let imageOldTraffordFootballClub : UIImage = UIImage(named: "oldTraffordStadium.jpg")!
let stadiumImage = (image: imageOldTraffordFootballClub)
}
if (globalVenueSelected == "Emirates Stadium"){
let imageEmiratesFootballClub : UIImage = UIImage(named: "emiratesStadium.jpg")!
let stadiumImage = (image: imageEmiratesFootballClub)
}
if (globalVenueSelected == "Wembley"){
let imageWembley : UIImage = UIImage(named: "wemblyStadium.jpg")!
let stadiumImage = (image: imageWembley)
}
if (globalVenueSelected == "O2 Arena"){
let imageO2Arena : UIImage = UIImage(named: "o2ArenaStadium.jpg")!
let stadiumImage = (image: imageO2Arena)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
哦,顺便说一句,变量globalVenueSelected是一个全局变量,我不知道它是否会影响任何东西,但它可能会改变代码。
感谢任何帮助,谢谢。
答案 0 :(得分:1)
请尝试以下代码。
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
var imageName: String!
switch globalVenueSelected {
case "Gillingham Football Club":
imageName = "gillinghamStadium.jpg"
case "Old Trafford":
imageName = "oldTraffordStadium.jpg"
case "Emirates Stadium":
imageName = "emiratesStadium.jpg"
case "Wembley":
imageName = "wemblyStadium.jpg"
case "O2 Arena":
imageName = "o2ArenaStadium.jpg"
default: break
}
self.stadiumImage.image = UIImage(named: imageName)
}
您应该将switch语句放在viewWillAppear(:)
中,因为您的IBOutlet
可能未在viewDidLoad
中设置。
此外,许多人认为最佳做法是使用反映该变量类型的变量名称。例如,
stadiumImage
应重命名为stadiumImageView
。logoImage
应重命名为logoImageView
。正确命名变量名称将使您和其他人更容易阅读,理解和维护您的代码。
此外,默认情况下,项目的资产目录通常不会接受.jpg
个文件。您可以将体育场图片转换为.png
格式,然后在设计时将其添加到资产目录中,或者您可以参考this Stack Overflow answer来解释如何让您的资产目录接受非PNG资源。