我正在使用iOS Swift App中添加Background:
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
然而,它直到底部才覆盖屏幕。我搜索了其他问题:
var backImage = UIImage(named: "background")
var resizablebackImage = backImage?.resizableImageWithCapInsets(UIEdgeInsets(top:10,left:0,bottom:10,right:0))
self.view.backgroundColor = UIColor(patternImage:resizablebackImage!)
这不起作用。有什么想法吗?
答案 0 :(得分:8)
如果您打算将其设置为背景图像,请不要将图像设置为图案颜色并将其填充为背景颜色。而是创建UIImageView
将图片设置为图片并将其添加到UIView
。
var bgImage = UIImage(named: "background");
var imageView = UIImageView(frame: self.view.bounds);
imageView.image = bgImage
self.view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
答案 1 :(得分:1)
请参阅下面的代码。只需将bgImageName
设置为您的图片名称,然后拨打setBackgroundImage()
即可。我在设备轮换的情况下添加了自动重载功能。
var bgImage = UIImage()
var bgImageView = UIImageView()
var bgImageName = ""
override func viewDidLoad() {
super.viewDidLoad()
bgImageName = "bg-orange" // or whatever your image is called
setBackgroundImage()
}
func setBackgroundImage() {
if bgImageName > "" {
bgImageView.removeFromSuperview()
bgImage = UIImage(named: bgImageName)!
bgImageView = UIImageView(frame: self.view.bounds)
bgImageView.image = bgImage
self.view.addSubview(bgImageView)
self.view.sendSubviewToBack(bgImageView)
}
}
// detect device orientation changes
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
print("rotated device to landscape")
setBackgroundImage()
} else {
print("rotated device to portrait")
setBackgroundImage()
}
}