How to set a background image in Xcode using swift?

IosSwiftBackground

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))
}

Solution 2 - Ios

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

Solution 3 - Ios

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

Solution 4 - Ios

SWIFT 4

view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage

Solution 5 - Ios

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)

Solution 6 - Ios

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)

Solution 7 - Ios

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

Solution 8 - Ios

SWIFT 5 for TableViewController

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

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

Solution 9 - Ios

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuiGui23View Question on Stackoverflow
Solution 1 - IosHayley GuillouView Answer on Stackoverflow
Solution 2 - IosMina FawzyView Answer on Stackoverflow
Solution 3 - IosDàChúnView Answer on Stackoverflow
Solution 4 - IosAliView Answer on Stackoverflow
Solution 5 - IosMark ThackerView Answer on Stackoverflow
Solution 6 - IosIryna BatvinaView Answer on Stackoverflow
Solution 7 - IosBabakHSLView Answer on Stackoverflow
Solution 8 - IosKuralay BiehlerView Answer on Stackoverflow
Solution 9 - IospudepiedView Answer on Stackoverflow