lr100
lr100

Reputation: 600

Dynamically Add and Center UIImages in UIView

I am trying to think through this fun "problem".

I have a UIView (288x36) that will hold up to 8 UIImages (36x36). Any number (up to 8) can be placed in the UIView. I want the "collection" of these images to be centered in the UIView.

If there is only 1 image, then it's center will be in the center of the UIView. If 2, then the max width of the image will be in the center of the UIView and the 2nd images starting point will also be in the center, etc etc.

Has anyone dealt with this before? Any code examples.

I am not very advanced but trying to learn.

Upvotes: 0

Views: 148

Answers (1)

extra
extra

Reputation: 60

Suppose your UIView is called view and your array of images is imageArray:

float remainingSpace = view.bounds.size.width - imageArray.count*36; //This is the space to remaining
float spaceOnLeft = remainingSpace/2.0; //Just the space to the left of the images
for (UIImage *image in images) {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(spaceOnLeft, 0, 36, 36)];
    imageView.image = image;
    [view addSubview:imageView];
    spaceOnLeft += 36.0; // so the next image is spaced 36 points to the right
}

Upvotes: 1

Related Questions