Stretch background to view in Swift

I am using adding background in iOS Swift app using:

 self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)

      

However, it doesn't cover the screen down to the bottom level. I searched Other questions:

var backImage = UIImage(named: "background")

var resizablebackImage = backImage?.resizableImageWithCapInsets(UIEdgeInsets(top:10,left:0,bottom:10,right:0))

self.view.backgroundColor = UIColor(patternImage:resizablebackImage!)

      

This does not work. Any ideas?

+3


source to share


2 answers


If you intend to set it as a background image, don't make the image as a template color and fill it as a background color. Create instead UIImageView

to set the image as an image and add it to UIView

.



var bgImage     = UIImage(named: "background");
var imageView   = UIImageView(frame: self.view.bounds);
imageView.image = bgImage
self.view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)

      

+7


source


For Swift 1.x and Swift 2 plus device rotation detection

See my code below. Just set bgImageName

to the name of your image and call setBackgroundImage()

. I added automatic reboot in case of device rotation.



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

      

+1


source







All Articles