2013-10-29 130 views
2

我想在主UIView中水平居中一些UIViews(它們恰好是圓圈)。它最終將基本上看起來像標準頁面控件上的點。水平居中多個UIView

我已經編寫了所有的代碼來創建圓UIViews我只是不知道如何在運行時水平和動態地安排它們。

基本上我需要某種水平的容器在那裏我可以做到這一點

-(void)addCircle{ 
    [self addSubView:[CircleView init]]; 
} 

,它會自動安排然而,許多孩子就在中央。

+0

試過'layoutSubviews'或自動佈局約束? – Wain

+0

你在使用哪種自動佈局或自動調整掩碼? – Lance

+0

我有限制啓用,但我發現他們非常反直覺相比,以及我用過的其他技術哈哈。我希望有人能建議最好的辦法做到這一點,因爲我從字面上不知道從哪裏開始...... – Chris

回答

10

我對自動佈局不時感到困惑,不過這裏有一種方法可以以編程方式進行:(我假設你將你的圓視圖添加到視圖控制器的containerView屬性中,添加任何其他意見的話)

  1. 這兩個屬性添加到您的視圖控制器:

    @property (nonatomic) CGRect circleViewFrame; 
    @property (nonatomic) CGFloat delta; 
    
  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; 
    
  3. 現在,我們添加 「自動addCircle法」:

    - (void)addCircleView { 
        UIView *newCircleView = [self createCircleView]; 
        [self.containerView addSubview:newCircleView]; 
        [self alignCircleViews]; 
    } 
    
  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; 
    } 
    
  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; 
        } 
    } 
    

這是最重要的方法,它會在每次添加新的circleView時自動重新對齊所有子視圖。其結果將是這樣的:

sample view controller with 3 horizontally centered subviews sample view controller with 8 horizontally centered subviews

+0

嘿米沙,我還沒有機會測試這個,但看起來很有前途的謝謝! – Chris

+0

像夢一樣工作 - 謝謝! – Chris

+0

很高興能有所幫助。 ;) – Mischa

0

簡單的步驟:追加圈容器視圖,調整大小容器視圖,居中對齊容器視圖

 
-(void)addToContanerView:(CircleView*)circle{ 

    circle.rect.frame = CGrectMake(containers_end,container_y,no_change,no_change); 
    [containerView addSubview:circle]; 
    [containerView sizeToFit]; 
    containerView.center = self.view.center; 
} 

假設: containers_end & containers_y可以從CGRectMax函數獲取, for UIView SizeToFit方法檢查here

爲了照顧輪換使用,請確保您的Autoresizing子視圖設置爲左側,右側底部和頂部邊距。