3

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?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
tika
  • 7,135
  • 3
  • 51
  • 82

2 Answers2

8

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)
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • what if the content is overlapped by the image? (i.e. buttons...) – MeV Mar 17 '15 at 13:24
  • 1
    @MaRco85: That' why we are adding the image as inner most child view. Check the code `self.view.sendSubviewToBack(imageView)` – Midhun MP Mar 17 '15 at 18:32
1

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()
    }
}
Sebastian
  • 8,952
  • 3
  • 32
  • 30