Ido Naveh
Ido Naveh

Reputation: 2492

Scale images of UIImage in UIStackView to fit screen size in iOS app

On my iOS app written in Swift 3, I have 4 UIImages, each 2 in a UIStackView, and the 2 UIStackViews inside another UIStackView, as shown in the picture below:

enter image description here

In the picture you can see the division I made to the images.

You can also see the problem, when the images are exiting the screen and the user can't see the full image because it's get cropped.

All images are on "2x" size on their Image Set in Assets.xcassets.

On Main.storyboard on the Attributes Inspector I changed the Content Mode to "Scale To Fill" for all 4 images. I also did that in code:

phoneCallImage.contentMode = UIViewContentMode.scaleAspectFit
sendEmailImage.contentMode = UIViewContentMode.scaleAspectFit
sendSmsImage.contentMode = UIViewContentMode.scaleAspectFit
openFacebookImage.contentMode = UIViewContentMode.scaleAspectFit

I also tried to do that with the full UIStackView (Images Stack View in the picture):

imagesStackView.contentMode = UIViewContentMode.scaleAspectFit

What can I do to fix this and show the full image without cropping it?

Upvotes: 1

Views: 3376

Answers (2)

user1488696
user1488696

Reputation:

You will need to set up constraints for the individual images and the containing stack views.

For each image you will need to specify a width constraint equal to the top most stack view with a multiplier of 0.5 (50% of parent width) so that it scales with the screen size.

Then for each image you may want to use a constraint for the aspect ratio to keep it 1:1 so that the height scales equally as well.

Then for the top stack view you'll want to constrain its width to the parent view as well and then add constraints for left margin and y position.

See images for the constraints and the final result.

You dont need the width constraints The end result

Upvotes: 1

Ido Naveh
Ido Naveh

Reputation: 2492

I managed to fix this.
First I selected the full UIStackView (Images Stack View in the picture) and added constraints to it, to set the margins to 0:

enter image description here

After that I chose everyone of the images in the UIStackView and changed its width and height to 171.5 from the constraints menu, in order it to be a square:

enter image description here

After that, everything was perfectly aligned into the screen.

Upvotes: 0

Related Questions