如何在 swift 中将图像居中放置在状态栏下方?

how to center an image under the status bar in swift?

我似乎找不到合适的代码。 我想在状态栏下方放置一个图像 20 点(这将是 Y)并将其居中(当然这将是 X)。 我可以用情节提要轻松地做到这一点,但我正在努力以编程方式做到这一点。 假设这是我的代码:

var image: UIImage = UIImage(named: "someImage.png")!
            var bgImage = UIImageView(image: image)
            //Tried with self.view.frame.size.height but not working
            bgImage.frame = CGRect(x: 0, y: self.view.frame.size.height - 20, width: self.view.frame.size.width, height: 64)

           //also tried this which not worked as well 
          //  bgImage.center = CGPointMake(self.view.frame.width, self.view.frame.hight - 20)
            self.view.addSubview(bgImage)

我已经搜索了 apple 文档,但还不清楚,如有任何帮助,我们将不胜感激。

这样的事情怎么样:

var image: UIImage = UIImage(named: "someImage.png")
var new_view = UIView(image: image)
view.addSubview(new_view);

// This is the default setting but be explicit anyway...
new_view.setTranslatesAutoresizingMaskIntoConstraints(true)

new_view.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin |
    UIViewAutoresizing.FlexibleRightMargin 
new_view.center = CGPointMake(self.view.frame.size.height - 20, view.bounds.midY)

它添加了新的子视图,在其上设置了灵活的左右边距,然后将其居中放置在状态栏下方。

我找到的程序代码 in this related question

一旦 bgImage 的大小正确,那么一般的解决方案是

bgImage.frame.origin.y = 20.0 // 20 down from the top
bgImage.frame.origin.x = (self.view.bounds.size.width - bgImage.frame.size.width) / 2.0 // centered left to right.