2017-05-25 63 views
0

我想根據我顯示的應用程序的哪一部分來更改UIImageView。Swift:基於IF更改UIImageView

在我的視圖控制器,這個工程設置圖像:

let screenSize = UIScreen.main.bounds 
let screenWidth = screenSize.width 
let screenHeight = screenSize.height 

let imageName = "sectionOneBackground" 
let image = UIImage(named: imageName) 
let imageView = UIImageView(image: image!) 
imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight) 
view.addSubview(imageView) 

但是,如果我換了圖像中的,如果像這樣:

var imageName = "" 

if (section == "one") { 
    imageName = "sectionOneBackground" 
} 

if (section == "two") { 
    imageName = "sectionTwoBackground" 
} 

if (section == "three") { 
    imageName = "sectionThreeBackground" 
} 

然後,它只是不出現在視圖。我完全錯過了些什麼。沒有這個更簡單的方法來改變視圖的背景嗎?

在此先感謝。

+0

你正在使用的ImageView作爲實例,創建你的圖像視圖作爲全球 –

+0

能打擾你,並要求張貼,作爲一個答案,告訴我怎麼樣?我是一個noob你看。 – JamesG

回答

1

創建ImageView的一個字符串名稱作爲全球

class ViewController: UIViewController 
{ 
var imageView : UIImageView! 
var imageName : String! 

} 

您viewDidLoad中創建的ImageView像

override func viewDidLoad() { 
    super.viewDidLoad() 

    let screenSize = UIScreen.main.bounds 
    let screenWidth = screenSize.width 
    let screenHeight = screenSize.height 

    imageName = "sectionOneBackground" 
    imageView = UIImageView(image: UIImage(named: imageName)!) 
    imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight) 
    view.addSubview(imageView) 

} 

終於

每當變更ImageView的名稱

if (section == "one") { 
imageName = "sectionOneBackground" 
} 

else if (section == "two") { 
imageName = "sectionTwoBackground" 
} 

else if (section == "three") { 
imageName = "sectionThreeBackground" 
} 
imageView.image = UIImage(named: imageName) 

設定的最終圖像名稱圖像視圖

imageView.image = UIImage(named: imageName) 
+0

非常感謝你:) – JamesG