69

How can I set a background image for my main view controller in Xcode 6 using swift? I know that you can do this in the assistant editor as below:

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.yellowColor()
}

What is the code to set the background to an image I have in my assets folder?

ajrlewis
  • 2,968
  • 3
  • 33
  • 67
GuiGui23
  • 4,035
  • 4
  • 19
  • 17
  • You looking for [UIColor.colorWithPatternImage](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIColor_Class/index.html#//apple_ref/occ/clm/UIColor/colorWithPatternImage:)? More on background image for UIView [here](http://beageek.biz/how-to-set-background-image-uiview/) – Xenyal Nov 20 '14 at 21:36

9 Answers9

132
override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))
}
Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34
  • 10
    I tried using it with a background image. There is an issue in this solution, as it puts the image in a repeating mode. – MhmdRizk Jul 24 '18 at 08:08
  • Setting an image as a background color is something I would consider to be very confusing. While it might work, I would highly suggest a different approach by simply adding an image view below your other content, similar to most of the other answers - https://stackoverflow.com/a/36309946/2985369 is the closest to correct. – mredig Nov 10 '20 at 21:02
53

I am beginner to iOS development so I would like to share whole info I got in this section.

First from image assets (images.xcassets) create image set .

According to Documentation here is all sizes need to create background image.

For iPhone 5:
   640 x 1136

   For iPhone 6:
   750 x 1334 (@2x) for portrait
   1334 x 750 (@2x) for landscape

   For iPhone 6 Plus:
   1242 x 2208 (@3x) for portrait
   2208 x 1242 (@3x) for landscape

   iPhone 4s (@2x)      
   640 x 960

   iPad and iPad mini (@2x) 
   1536 x 2048 (portrait)
   2048 x 1536 (landscape)

   iPad 2 and iPad mini (@1x)
   768 x 1024 (portrait)
   1024 x 768 (landscape)

   iPad Pro (@2x)
   2048 x 2732 (portrait)
   2732 x 2048 (landscape)

call the image background we can call image from image assets by using this method UIImage(named: "background") here is full code example

  override func viewDidLoad() {
          super.viewDidLoad()
             assignbackground()
            // Do any additional setup after loading the view.
        }

  func assignbackground(){
        let background = UIImage(named: "background")

        var imageView : UIImageView!
        imageView = UIImageView(frame: view.bounds)
        imageView.contentMode =  UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        imageView.image = background
        imageView.center = view.center
        view.addSubview(imageView)
        self.view.sendSubviewToBack(imageView)
    }
Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156
35
override func viewDidLoad() {

    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "bg_image")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectfill
    self.view.insertSubview(backgroundImage, at: 0)

}

Updated at 20-May-2020:

The code snippet above doesn't work well after rotating the device. Here is the solution which can make the image stretch according to the screen size(after rotating):

class ViewController: UIViewController {

    var imageView: UIImageView = {
        let imageView = UIImageView(frame: .zero)
        imageView.image = UIImage(named: "bg_image")
        imageView.contentMode = .scaleToFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.insertSubview(imageView, at: 0)
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: view.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
}
DàChún
  • 4,751
  • 1
  • 36
  • 39
  • 2
    This worked for me, however as of 2017, UIScreen.mainScreen().bounds is now UIScreen.main.bounds and self.view.insertSubview(backgroundImage, atIndex:0) is self.view.insertSubView(backgroundImage, at:0) – jffgrdnr Nov 08 '17 at 14:29
  • `.scaleToFill` will distort the image drastically with a rotate. If you're putting in a gradient or something where aspect ratio doesn't matter, that will be fine, but your initial answer is actually what most people will probably want. Apart from that, combining the `scaleAspectFill` and constraining to the view, *this* is the correct answer. (side note, it's not strictly necessary to `insert` the image view as opposed to `addSubview`, unless you add the views out of order. Adding subviews layer on top of each other, so as long as the background is first, it will be the background) – mredig Nov 10 '20 at 21:00
24

SWIFT 4

view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage
Adrian P
  • 6,479
  • 4
  • 38
  • 55
Ali
  • 2,427
  • 22
  • 25
12

You can try this as well, which is really a combination of previous answers from other posters here :

    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "RubberMat")
    backgroundImage.contentMode =  UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)
Mark Thacker
  • 121
  • 1
  • 2
12

For Swift 4

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "bg_name.png")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
Iryna Batvina
  • 1,656
  • 13
  • 7
2

Background Image from API in swift 4 (with Kingfisher) :

import UIKit
import Kingfisher

extension UIView {

func addBackgroundImage(imgUrl: String, placeHolder: String){
    let backgroundImage = UIImageView(frame: self.bounds)
    backgroundImage.kf.setImage(with: URL(string: imgUrl), placeholder: UIImage(named: placeHolder))
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.insertSubview(backgroundImage, at: 0)

}
}

Usage:

someview.addBackgroundImage(imgUrl: "yourImgUrl", placeHolder: "placeHolderName")
BabakHSL
  • 622
  • 1
  • 8
  • 18
1

SWIFT 5 for TableViewController

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)

tableView.backgroundView = UIImageView(image:"image.jpg")
tableView.backgroundView?.contentMode = .scaleToFill
}
0

Swift 5.3 in XCode 12.2 Playgrounds

Place the cursor wherever in the code the #insertLiteral would have been in earlier versions. Select from the top-menu Editor->Insert Image Literal... and navigate to the file. Click Open.

The file is added to a playground Resource folder and will then appear when the playground is run in whichever view it was positioned when selected.

If a file is already in the playground Bundle, e.g. in /Resources, it can be dragged directly to the required position in the code (where it will be represented by an icon).

cf. Apple help docs give details of this and how to place other colour and file literals.

pudepied
  • 799
  • 6
  • 5