1

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 ?

4

1 回答 1

3

像这样的东西应该工作。我将容器传递给函数,确定所有可见子视图的宽度,并从容器宽度和可见子视图的宽度中获取 x 偏移量。从那里,您可以更新可见子视图的框架,它们应该水平居中。

-(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;
       }
   }      
}

您必须更新它以包含视图之间的任何填充。

于 2013-07-22T18:17:02.053 回答