在Swift中的视图的拉伸背景

时间:2015-01-10 05:23:41

标签: ios swift ios8 ios8.1

我正在使用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!)

这不起作用。有什么想法吗?

2 个答案:

答案 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)

对于Swift 1.x& Swift 2加上设备旋转检测

请参阅下面的代码。只需将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()
    }
}