X Pahadi
X Pahadi

Reputation: 7463

Stretch Background for View in Swift

I am using adding Background in iOS Swift App using:

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

However, it does not cover the Screen till bottom. 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!)

That does not work. Any ideas?

Upvotes: 3

Views: 4164

Answers (2)

Sebastian
Sebastian

Reputation: 9051

For Swift 1.x & Swift 2 plus Device Rotation Detection

Please see my code below. Just set bgImageName to the name of your image and call setBackgroundImage(). I added an auto-reload in case of a 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()
    }
}

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107231

If your intention is to set it as the background image, don't make image as pattern color and fill it as background color. Instead create an UIImageView set your image as it's image and add it to your UIView.

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

Upvotes: 8

Related Questions