Pierre
Pierre

Reputation: 11633

Auto center UIViews

I'm a bit stuck with horizontal position on views. I have a lot a views in a view container (that's bigger than subviews total width).

All views must be horizontally centered. If a subview is marked as hidden (or with a zero alpha), the position of the others must change to be centered again.

Do you have an idea how I can do that ?

Upvotes: 1

Views: 175

Answers (1)

JeffRegan
JeffRegan

Reputation: 1322

Something like this should work. I pass the container into the function, determine the width of all the visible subviews, and get the x offset from the container width and the width of the visible subviews. From there, you can update the frame of the visible subviews and they should be centered horizontally.

-(void)centerViews:(UIView*)container {
   CGFloat width = 0.0;
   for(UIView *view in container.subviews) {
       if(view.alpha > 0.0) {
           width += view.frame.size.width;
       }
   }

   CGFloat xOffset = (container.frame.size.width - width) / 2.0;

   for(UIView *view in container.subviews) {
       if(view.alpha > 0.0) {
           [view setFrame:CGRectMake(xOffset, view.frame.origin.y, view.frame.size.width, view.frame.size.height)];

            xOffset += view.frame.size.width;
       }
   }      
}

You'll have to update this to include any padding you have between views.

Upvotes: 3

Related Questions