简体   繁体   English

将UIImageView子视图作为背景添加到UIImageView不起作用

[英]add UIImageView subview as background to UIImageView not working

I am trying to add an UIImageView as a Subview to an existing UIImageView, to get a Backgroundimage, which can be set to AspectFit. 我试图将UIImageView作为子视图添加到现有的UIImageView,以获取Backgroundimage,可以将其设置为AspectFit。

So I tried to do this: 所以我尝试这样做:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var photo: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        photo.image = UIImage(named:"test.png")
        photo.contentMode = .scaleAspectFill

        let width = self.photo.bounds.size.width
        let height = self.photo.bounds.size.height

        let imageViewBackground = UIImageView(frame: CGRect(x:0,y:0,width:width,height:height))
        imageViewBackground.image = UIImage(named:"DG.png")

        imageViewBackground.contentMode = .scaleAspectFit

        photo.addSubview(imageViewBackground)
        photo.sendSubviewToBack(imageViewBackground)
    }
}

But "DG.png" is always displayes in front of "test.png". 但是,“ DG.png”始终显示在“ test.png”的前面。 I also tried to insert the subview at index 0, and I've also tried to add that code in the extension of UIImageView, but nothing worked. 我还尝试将子视图插入索引0,并且还尝试在UIImageView的扩展名中添加该代码,但没有任何效果。

Can someone please explain me, why this isn't working? 有人可以解释一下,这为什么不起作用?

Thanks! 谢谢!

If you add a view as a subview of another view it will be always in front of the parent view. 如果将一个视图添加为另一个视图的子视图,它将始终位于父视图的前面。

why don't you use the first imageview for the background and add the photo as the subview? 为什么不将第一个图像视图用作背景,并将照片添加为子视图? and why are you adding the imageview in code ? 以及为什么要在代码中添加imageview? you could just add the imageview in the storyboard. 您可以仅在情节提要中添加imageview。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM