水平居中多个UIViews

Chr*_*ris 2 iphone objective-c uiview ios

我想在主UIView中水平居中一些UIViews(它们恰好是圆圈).它最终基本上看起来像标准页面控件上的点.

我已经编写了所有代码来创建圆圈UIViews我只是不知道如何在运行时水平和动态地安排它们.

基本上我需要某种水平容器,我可以这样做

-(void)addCircle{
  [self addSubView:[CircleView init]];
}
Run Code Online (Sandbox Code Playgroud)

它将自动安排它在中心的许多孩子.

Mis*_*cha 10

我也不时地对自动布局感到困惑,但这是一种如何以编程方式进行的方式:(我假设您将圆视图添加到containerView视图控制器的属性中,并且不添加任何其他视图到它.)

  1. 将这两个属性添加到视图控制器:

    @property (nonatomic) CGRect circleViewFrame;
    @property (nonatomic) CGFloat delta;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在视图控制器的viewDidLoad方法中使用所需的值启动这些属性:

    // the size (frame) of your circle views
    self.circleViewFrame = CGRectMake(0, 0, 10, 10);
    // the horizontal distance between your circle views
    self.delta = 10.0;
    
    Run Code Online (Sandbox Code Playgroud)
  3. 现在我们添加"自动addCircle方法":

    - (void)addCircleView {
      UIView *newCircleView = [self createCircleView];
      [self.containerView addSubview:newCircleView];
      [self alignCircleViews];
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 当然我们需要实现这个createCircleView方法......

    - (UIView*)createCircleView {
      // Create your circle view here - I use a simple square view as an example
      UIView *circleView = [[UIView alloc] initWithFrame:self.circleViewFrame];
      // Set the backgroundColor to some solid color so you can see the view :)
      circleView.backgroundColor = [UIColor redColor];
    
      return circleView;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. ......和alignCircleViews方法:

    - (void)alignCircleViews {
      int numberOfSubviews = [self.containerView.subviews count];
      CGFloat totalWidth = (numberOfSubviews * self.circleViewFrame.size.width) + (numberOfSubviews - 1) * self.delta;
      CGFloat x = (self.containerView.frame.size.width / 2) - (totalWidth / 2);
    
      for (int i = 0; i < numberOfSubviews; i++) {
          UIView *circleView = self.containerView.subviews[i];
          circleView.frame = CGRectMake(x,
                                  self.circleViewFrame.origin.y,
                                  self.circleViewFrame.size.width,
                                  self.circleViewFrame.size.height);
          x += self.circleViewFrame.size.width + self.delta;
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)

这是最重要的方法,每次添加新的circleView时,它都会自动重新排列所有子视图.结果将如下所示:

具有3个水平居中子视图的示例视图控制器 具有8个水平居中子视图的示例视图控制器