2015-07-19 24 views
0

我想根據數組中的按鈕數來中心按鈕。基於陣列中n個圖像的視圖中的中心圖像

因此,與一個對象,你會通過以下居中:

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

然而,當我在一個數組對象的n個,我有一個很難中心他們。以下是我有這麼遠,但它從來沒有對齊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]; 
    } 
} 

而這正是我結束了:

image1

從外觀上來看FB圖標的起源是在寬度的一半處開始,但我無法得到正確的結果。請幫助我瞭解執行此操作的過程,無論是更好的方式還是以這種方式進行修復。謝謝。

回答

1

第一偏移量=半寬度 - 所有按鈕寬度的一半。也許你需要考慮視圖無法顯示連續按鈕的情況。

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

很好地完成。謝謝 –