如何让图像覆盖整个UIView?

时间:2018-01-11 02:52:16

标签: ios swift uiview size bounds

我在下面的代码中将图像放在视图上。问题是,从iPhone转移到iPad时,创建固定的高度和宽度不起作用。我希望代码能够传输整个画布,而不是固定数量。

@IBOutlet weak var jj: draw!

override func viewDidLoad() {
    super.viewDidLoad()

    let image = UIImage(named: "se")
    let imageView = UIImageView(image: image!)
    imageView.frame = CGRect(x: 0, y: 0, width: 200, height: 300)
    jj.addSubview(imageView)
}

4 个答案:

答案 0 :(得分:0)

如您希望覆盖jj视图上的imageView。 此代码将正常运行。

@IBOutlet weak var jj: draw!
private var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad((

    self.imageView = UIImageView(image : UIImage(named: ”se”) )
    // set properties blah blah as your code
   // but do not addSubview to Outlet in viewDidLoad
   // they are not initialized yet
}

override func viewWillAppear( _ animated: Bool) {
    super.viewWillAppear(animated);

    // this method can be called multiple times as the view controller presented or dismissed
    // so make sure the imageView is added to superview if it’s not added
    if self.imageView.superview == nil {
        jj.addSubview(imageView);
    }
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
     // layout your responsive code here
     // you wish to cover your image view upon your jj view
     imageView.frame = CGRect(origin: .zero, size: jj.frame.size)
}

答案 1 :(得分:0)

您可以轻松使用自动布局来完成此任务。

      let backgroundImage : UIImageView = {
        let image = UIImageView(image: #imageLiteral(resourceName: "name-of-image"))
        image.translatesAutoresizingMaskIntoConstraints = false
        image.contentMode = .scaleToFill
        return image
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpView()
    }

    func setUpView(){
        view.addSubview(backgroundImage)
        NSLayoutConstraint.activate([
            backgroundImage.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            backgroundImage.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            backgroundImage.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            backgroundImage.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
        ])
    } 

答案 2 :(得分:0)

请尝试以下操作,希望它可以帮助您。

override func viewDidLoad() {
super.viewDidLoad((

self.imageView.layer.contents = #imageLiteral(resourceName: "se");
// In place of #imageLiteral(resourceName: "se"), you can write your image name 
}

答案 3 :(得分:0)

我建议你在故事板中这样做。使用AutoLayout enter image description here

所以它在每个设备中看起来都一样。 iphone 8 plus ipad