iOS autolayout - gap between image and top of the screen, despite constraints set

I have an image that i would like to place in the top part of the screen. I've set its mode to aspect fit, because i want to preserve original ratio. I've also set left, top and right constraints to 0:

enter image description here

Despite the fact that the top constraint is set to 0, there is a lot of empty space between the image and top of the screen which is definitely not what i want:

enter image description here

Only when i set top constraint to about "-100" i get something similar to what i would like to achieve:

enter image description here

Could you please explain me such non intuitive behaviour and tell me what should i do to place the image on the top of the screen without any gaps - like on the image above.

Upvotes: 3

Views: 1500

Answers (4)

After some trials an errors i come up with something that is 99% of what i originally wanted. Left, top and right constraint has to be set to 0, aspect ratio constraint also has to be enabled. On top of that "Scale to fill" mode. This works quite well besides that fact that you have to calculate the correct image ratio on your own.

Upvotes: 1

Travis M.
Travis M.

Reputation: 11257

This is worth a try, if you are still having this issue.

Tap on your ViewController and then uncheck the below properties. See if that fixes the problem.

enter image description here

Upvotes: 2

Rory McKinnel
Rory McKinnel

Reputation: 8014

It would seem this is not that easy to solve: How do I autoresize an image, but at the top of the ImageView (programmatically in Xcode)?

Problem is you really want aspect fill and top at the same time.

My suggestion would be to take your UIImageView and add a cosnstraint for the aspect ratio as well as what you already have. Then Ctrl-drag from this constraint into the .h file of your view controller and create an IBOutlet.

This gives you an IBOutlet you can use in your code to adjust the aspect ratio of the UIImageView.

When you load your image in the code, inspect the image and calculate its aspect ratio. Set the constraint IBOutlet constant to match. This should then force the UIImageView to align itself aspect ration wise with the image and the constrains should then pull it all into place.

Upvotes: 0

Nikita Arkhipov
Nikita Arkhipov

Reputation: 1258

As I can see from your screenshot your image frame is much bigger than the image content. In case you want to have that frame consider setting Aspect Fill to image mode. Otherwise you should set following constraints: enter image description here

Hope this will help.

Upvotes: 1

Related Questions