4

I have an UIImageView in the in the controller's view with a distance of 20% of the screen height from the top of the view. ie I want to set the 20 % of the screen height as the top Constraint of the UIImageView.

Can I implement this without adding a transparent view, which is how I do it now (by setting its height to be 20% of the screen Height), to the container view ?

jscs
  • 63,694
  • 13
  • 151
  • 195
jkdev
  • 93
  • 1
  • 9

3 Answers3

10

Set the top constraint of your UIImageView to bottom of the main view, with constant 0, multiplier 0.2 or 2:10

Reason: the coordinate of your main view bottom is equal to the height of it ( the top most view of the controller).

Edit: Step by Step

  1. Add constraint from top UIImageView to top of the main view (like you normally do).
  2. Go into the detail of that constraint, change main view top to 2nd item if needed, and set it to main view bottom instead of top.
  3. set constraint constant 0, multiplier 0.2 or 2:10
Duy Pham
  • 211
  • 1
  • 4
4

You can do it in the IB/StoryBoard itself. Since you want the top vertical space between the image view and it's superview to be always 20% of the height of the superview, it is same as setting the image view's height to be 80% of it's superview's height and pinning the bottom of image view to the bottom of it's superview. Hence, you can eliminate that transparent view from being added.

Steps (I'm only considering vertical constraints here):
1. Drag a constraint from the bottom of the image view to the bottom of it's superview.
2. Drag an equal heights constraint from the image view to it's superview. Change the multiplier value of this constraint to 8:10 in the Size Inspector (Screenshot's attached below).

Size Inspector

Ganesh Kamath
  • 1,181
  • 11
  • 20
  • 1
    Here we can set the top Constraint but we cannot adjust the height thereafter according to the contained image . – jkdev Nov 30 '15 at 05:19
1

Take the Spacer View at top & give its height proportional height of 20% then give top constrain to your imageView with the spacerView & Done

Mihawk
  • 581
  • 4
  • 12
  • Thank you for replying. But that is what I do . I wanted to know if I can achieve this without any additional view added to the superView.. – jkdev Nov 27 '15 at 07:27
  • i do not think their is any better way to do this. – Mihawk Nov 27 '15 at 07:38
  • I had the same thought until I discovered constraint with different attributes, that is the best way to do this, AFAIK – Duy Pham Nov 29 '15 at 01:12