Search code examples
swiftuiviewuiviewcontrolleruiimageviewuiimage

Set view background from image view


I am trying to match whatever image is placed in a UIImageView with the background image of the view controller's view. So when the user calls func call in the example below, whatever image is in the image view choosenBack is displayed as the background of the view controller. If no image is placed in the image view, the view background image should just be nil.

choosenBack = UIImageView()

func call(){
    self.view.backgroundColor == UIColor(patternImage: UIImage(choosenBack)!)
}

Solution

  • Using the backgroundColor property will only work when you indeed want the image to be repeated to fill the background. In that case you could simply do something like

    func call() {
        if let image = choosenBack.image {
            self.view.backgroundColor = UIColor(patternImage: image)
        } else {
            self.view.backgroundColor = .white // Or w/e your default background is
        }
    }
    

    If you want the background image to not repeat, you'll need to use a dedicated background image view.

    let background = UIImageView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        background.contentMode = .scaleAspectFit // Or w/e your desired content mode is
    
        view.insertSubview(background, at: 0)
        background.translatesAutoresizingMaskIntoConstraints = false
        background.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        background.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        background.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        background.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    
        ...
    }
    
    func call() {
        self.background.image = choosenBack.image
    }