Search code examples
xcodeimageswiftcenter

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


I just can't seem to find the right code for it. I want to place an image 20 points under the status bar (this will be the Y) and center it (this would be the X of course). I can easily do it with storyboard but i'm struggling to do it programatically. supposed this is my code:

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)

I've search apple docs but it's so unclear, any help would be appreciated.


Solution

  • Once bgImage has the correct size, then the general solution for this is

    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.