ric*_*chc 2 background uiviewcontroller swift
我有一个UIViewController我想将背景设置为一个图像.我想在代码中执行此操作IB,因此我可以随后更改图像.
阅读了有关.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?
}
Run Code Online (Sandbox Code Playgroud)
小智 5
最好为此创建一个单独的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
}
Run Code Online (Sandbox Code Playgroud)