Search code examples
iosalignmentcgrectmake

Center images in view based on n images in array


I'm trying to center buttons based on the number of buttons in my array.

So with one object you would center it by the following:

CGRect originalFrame = self.view.frame;
button.frame = CGRectMake(orignalFrame.size.width/2 - self.button.frame.size.width/2, etc, etc, etc);

However, when I have n number of objects in an array I'm having a hard time centering them. Here is what I have so far but it never aligns x:

-(void)displayIconsFromSignedInArray:(NSArray *)array {
  CGFloat buttonWidthHeight = 50;

  CGFloat x = (self.view.frame.size.width / array.count) - (buttonWidthHeight / 2)*array.count;

  for (UIButton *button in array) {
    button.frame = CGRectMake(x, self.view.frame.size.height/2 - buttonWidthHeight/2, buttonWidthHeight, buttonWidthHeight);
    x += buttonWidthHeight + 2.5;
    [self.view addSubview:button];
  }
}

And this is what I end up with:

image1

From the looks of it the origin of FB icon is starting at half of the width but I can't get this right. Please help me understand the process of doing this, either a better way or fixing this way. Thank you.


Solution

  • first offset = half width - half all button width. Maybe you need to consider the situation that the view can't display the button in a row.

      CGFloat x = self.view.frame.size.width/2 - buttonWidthHeight*array.count/2;