如何设置UIViewController背景图像来填充屏幕
我有一个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?
}
创建的形象图,该图像添加到图像视图和图像视图添加到您的视图层次。
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)
}
感谢卢卡斯现在排序。 – richc
最好为此创建一个单独的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
}
谢谢RM_B。现在排序。 – richc
我只是将loadView()方法中的最后一行更改为:self.imageView.frame = UIScreen.main.bounds(所以适用于我)。可能对某人有帮助...... –
你在哪里设置背景图片? – Lukas
背景图像设置在别处。该部分工作正常,因为图像的某些部分显示,但它没有正确填写 – richc