How to fill background image in subview in swift 4?

I have used scrollview. Over the Scrollview I have a UIView where I can set up my image as a background. But problem is that image height is not merged with UIView height. It is shown when scrolling bottom. I want add image with whole UIView. Here is my image screen shot

enter image description here

Here is my code

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.clipsToBounds = true
backgroundImage.image = UIImage(named: "background_image")
backgroundImage.contentMode = .scaleToFill
self.my_view_2.insertSubview(backgroundImage, at:0)

Please Help me Thanks

4 answers

  • answered 2018-04-17 05:37 Wendra

    try this

    let backgroundImage = UIImageView(frame: my_view_2.bounds)
    backgroundImage.clipsToBounds = true
    backgroundImage.image = UIImage(named: "background_image")
    backgroundImage.contentMode = .scaleToFill
    self.my_view_2.addSubview(backgroundImage)
    

  • answered 2018-04-17 05:49 Jaydeep Patel

    Add this code in your viewDidLoad(). May be helps you to solve.

    if #available(iOS 11.0, *) {
       scrollView.contentInsetAdjustmentBehavior = .never
    } else {
       automaticallyAdjustsScrollViewInsets = false
    }
    

  • answered 2018-04-17 05:54 user816

    Hope it may help

    self.my_view_2.layer.contents = #imageLiteral(resourceName: "background_image");
    

  • answered 2018-04-17 06:28 Ankit Jayaswal

    Height of your UIImageView is same as screen size, if your view is greater than screen size, then white view will remain at bottom.

    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    

    Update frame of backgroundImage with scroll's view, as:

    let backgroundImage = UIImageView(frame: self.my_view_2.bounds)
    backgroundImage.autoresizingMask = [.flexibleHeight, .flexibleWidth] // In case if your my_view_2 frames increases
    self.my_view_2.insertSubview(backgroundImage, at: 0)