简体   繁体   中英

Swift change position of UIImageView

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.

在此处输入图片说明

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)

Add another UIView to the top section of your scroll view. Adjust it the height you want. Do layout constraints and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM