3

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.

XcodeNOOB
  • 2,135
  • 4
  • 23
  • 29

2 Answers2

10

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.
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • Was just wondering, if I want the Y to be 20 points up from the bottom, how should i write the code? plus, where can i find docs about it? – XcodeNOOB Jan 28 '15 at 00:08
  • 1
    `bgImage.frame.origin.y = (self.view.bounds.size.height - bgImage.frame.size.height) - 20.0`. When I get confused, I draw things out on a piece of paper, but read [View and Window Architecture](https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/WindowsandViews/WindowsandViews.html) to get a base understanding. – Jeffery Thomas Jan 28 '15 at 11:10
2

how about something like this:

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)

Which adds the new subview, sets a flexible left & right margin on it and then centers it just under the status bar.

The programmatic code for which I found in this related question.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215