Reputation: 1531
I am adding a image view by code, and setting the image aspect fit to be ScaleAspectFit.
What I can't get to work is the top space/constraint of the image. I would like to have the image set at a specific space to the top while keeping the ScaleAspectFit.
When you swipe between the images the all have a different top position which looks odd.
My structure is page view controller > scroll view. In order to add zoom to the images.
code for adding the image:
imageView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height)
imageView.contentMode = .ScaleAspectFit
imageView.url = imageFileName?.toURL()
imageView.userInteractionEnabled = true
scrollView.addSubview(imageView)
And here is a print screen to show the problem. What I am trying to do is to always make the black space to the top have the same height of all images. So that they all have the same top space.
Upvotes: 0
Views: 3789
Reputation: 203
Instead of using .ScaleAspectFit
you can use .ScaleAspectFill
which guarantees that the image always completely fills the view. Then none of the image views will have uneven empty space at the top.
If you must have .ScaleAspectFit
behavior, then you can calculate the "aspect fitting" frame of the image and set its frame manually so that it fits and is top aligned:
import AVFoundation
...
let aspectRatio = imageView.image.size.width / imageView.image.size.height
let aspectRect = AVMakeRectWithAspectRatioInsideRect(aspectRatio, scrollView.bounds)
imageView.frame = CGRectMake(0, 0, aspectRect.size.width, aspectRect.size.height)
Upvotes: 1
Reputation: 1849
Add another UIView to the top section of your scroll view. Adjust it the height you want. Do layout constraints and it should work.
Upvotes: 0