Search code examples
iosobjective-cuiviewuiimageviewxcode-storyboard

How to set an image as background directly on a view without using imageview?


 UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.jpg"]];
    _mainView.backgroundColor = background;

When i run this code, i am getting image as background on the view but like several patterns. I want to set image to my view without using ImageView. Is it possible to do via stroyboard?


Solution

  • you may use CaLayer object, assign your image as content of view's layer. other items can be added as view's subviews as before.

    class CustomViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // assign image as content of view's layer
            view.layer.contents = UIImage(named: "yourImageName")!.cgImage
        }   
    } 
    

    for more info:

    Apple's CALayer doc

    CALayer tutorial