2015-11-04 191 views
2

我有一個UIViewController,我想將背景設置爲一個圖像。我想在代碼不是IB,所以我可以隨後更改圖像。如何設置UIViewController背景圖像來填充屏幕

在閱讀了關於.ScaleAspectFill的所有提示後,我的圖片仍然無法調整以適應屏幕。任何人都可以提供任何建議嗎?我的代碼是:

override func viewDidLoad() { 
    super.viewDidLoad() 

    // set the inital backgroundColor 
    self.view.backgroundColor = UIColor(patternImage: gameBackgroundOne!) 
    self.view.contentMode = UIViewContentMode.ScaleAspectFill //doesnt seem to do anything! 
    self.view.clipsToBounds = true // is this needed? 
    self.view.center = view.center // is this needed? 
} 
+0

你在哪裏設置背景圖片? – Lukas

+0

背景圖像設置在別處。該部分工作正常,因爲圖像的某些部分顯示,但它沒有正確填寫 – richc

回答

1

創建的形象圖,該圖像添加到圖像視圖和圖像視圖添加到您的視圖層次。

override viewDidLoad() { 
    super.viewDidLoad() 

    let imageView = UIImageView(frame: self.view.bounds) 
    imageView.image = UIImage(named: "your image name")//if its in images.xcassets 
    self.view.addSubview(imageView) 
} 
+0

感謝盧卡斯現在排序。 – richc

4

最好爲此創建一個單獨的UIImageView。

var imageView: UIImageView! 

override func loadView() { 
    super.loadView() 

    // get the correct image out of your assets cataloge 
    let image = UIImage(named: "yourImageInAssets")! 

    // initialize the value of imageView with a CGRectZero, resize it later 
    self.imageView = UIImageView(frame: CGRectZero) 

    // set the appropriate contentMode and add the image to your imageView property 
    self.imageView.contentMode = .ScaleAspectFill 
    self.imageView.image = image 

    // add the imageView to your view hierarchy 
    self.view.addSubview(imageView) 
} 

override func viewDidLayoutSubviews() { 
    super.viewDidLayoutSubviews() 

    //set the frame of your imageView here to automatically adopt screen size changes (e.g. by rotation or splitscreen) 
    self.imageView.frame = self.view.bounds 

} 
+0

謝謝RM_B。現在排序。 – richc

+0

我只是將loadView()方法中的最後一行更改爲:self.imageView.frame = UIScreen.main.bounds(所以適用於我)。可能對某人有幫助...... –

相關問題