How do you make a background image scale to screen size in swift?

前端 未结 9 2087
刺人心
刺人心 2020-11-27 04:27

I\'m trying to make a UIView image for my background in swift using pattern image. The code I have works well except for the fact that I want the image to take the whole scr

9条回答
  •  时光取名叫无心
    2020-11-27 05:03

    This is the updated answer of my previous one.

    As the same approach of my previous answer, You can create an extension of UIView and add addBackground() method to it, as follows:

    Remember: if you are adding it in a new .swift file, remember to add import UIKit

    extension UIView {
        func addBackground(imageName: String = "YOUR DEFAULT IMAGE NAME", contentMode: UIView.ContentMode = .scaleToFill) {
            // setup the UIImageView
            let backgroundImageView = UIImageView(frame: UIScreen.main.bounds)
            backgroundImageView.image = UIImage(named: imageName)
            backgroundImageView.contentMode = contentMode
            backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
    
            addSubview(backgroundImageView)
            sendSubviewToBack(backgroundImageView)
    
            // adding NSLayoutConstraints
            let leadingConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0)
            let trailingConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0)
            let topConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0)
            let bottomConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0)
    
            NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
        }
    }
    

    Note that the updates for this answer are:

    • Swift 4 code

提交回复
热议问题