简体   繁体   中英

IOS Autolayout- Multiple images in one horizontal line of subview programmatically

I created a tableview header and added a subview to it. I am trying to center multiple avatar images(fixed width and height) in a single line of this ui subview.

Max number of images=max(predefined). Number of images that I would like to fit is n.

When 5 is max number of image,

n=1:

[......................image 1........................... ]

n=2:

[.................image 1.....image2...............]

n=3

[.........image 1.....image2....image3.........]

n=4

[...image 1....image2....image3......image4...]

n=5

[.imag 1....imag2....imag3....imag4....imag5.]

That is the placement should be centred with equal spacings.

How can I achieve this programatically?

I can do this by story board, by placing max images in a row, keeping equal leading and trailing spaces, and when n=1, i will hide 1,2,4 and 5

while when n=2, i will hide 1,2,5

If you can target a Deployment Target of iOS 9 and up, use UIStackView . It's designed to handle this scenario.

If you can't do that yet, the following algorithm will work. It doesn't use constraints.

CGFloat tableWidth = ...; // This may change if you allow rotation.
CGFloat spacer = ...; // Amount of space between images goes here.
CGFloat imageWidth = images.count > 0 ? [[images[0] size] width] : 0.0;
CGFloat imageHeight = images.count > 0 ? [[images[0] size] height] : 0.0;
CGFloat totalWidth = images.count * imageWidth + (images.count - 1) * spacer;
CGFloat leftEdge = (tableWidth / 2.0) - (totalWidth / 2.0);

for (int i = 0; i < images.count; i++) {
    UIImageView *iv = ...; // Create and configure with image[i].

    CGRect frame = CGMakeRect(0, 0, imageWidth, imageHeight);
    frame.origin.x = leftEdge + (i * imageWidth + i * spacer);
    iv.frame = frame;
}

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