拉伸背景以在 Swift 中查看

Stretch Background for View in Swift

我在 iOS Swift 应用程序中添加背景使用:

 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!)

那是行不通的。有什么想法吗?

如果您打算将其设置为背景图片,请不要将图片设置为图案颜色并将其填充为背景颜色。而是创建一个 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)

对于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()
    }
}