2012-07-23 32 views
0

我想添加一個在另一個下方的按鈕。我有這個簡單的代碼:將按鈕添加到另一個下方

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    for(int i=0 ; i<9 ; i++) 
    { 
     UIButton *myButton = [[UIButton alloc] init]; 
     myButton.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height/10); //this "10" i want also dynamically 
     myButton.backgroundColor = [UIColor blackColor]; 
     [self.view addSubview:myButton]; 
    } 

} 

當然,我知道它會畫一個在另一個。但我可以在不知道高度的循環中做到這一點(因爲高將取決於循環中將有多少個按鈕)。

我想達到的目標:

Buttons

+0

但是,如果你添加100個按鈕,他們會有點小,不是嗎?爲什麼不將按鈕添加到uiscrollview? – divol 2012-07-23 08:04:56

+0

如果我想出如何添加一個在另一個下面,這不會是一個問題添加滾動視圖。 – Kuba 2012-07-23 08:09:02

回答

1

試試這個:

- (void)viewDidLoad 
    { 
    [super viewDidLoad]; 
    int number = 10; 

    for(int i=0 ; i<9 ; i++) 
    { 
    UIButton *myButton = [[UIButton alloc] init]; 
    myButton.frame = CGRectMake(self.view.frame.origin.x, (self.view.frame.size.height/number)*i + number, self.view.frame.size.width, self.view.frame.size.height/number); 
    myButton.backgroundColor = [UIColor blackColor]; 
    [self.view addSubview:myButton]; 
    } 


} 
+0

非常感謝,非常簡單和有效! :) – Kuba 2012-07-23 08:30:22

+0

不客氣.. :) – Nilesh 2012-07-23 08:31:08

0

也許,這可能會奏效?對不起,我還沒有使用self.view.frame年齡,但你得到的一般想法。

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    int number; 

    for(int i=0 ; i<9 ; i++) 
    { 
     UIButton *myButton = [[UIButton alloc] init]; 
     myButton.frame = CGRectMake(i * self.view.frame.origin.x/number, 
            self.view.frame.origin.y, 
            self.view.frame.size.width, 
            self.view.frame.size.height/number); //this "10" i want also dynamically 
     myButton.backgroundColor = [UIColor blackColor]; 
     [self.view addSubview:myButton]; 
    } 
} 
0

您需要定義按鈕的尺寸爲正確的節目,可惜沒有按鈕的大小,你不能達到你想因爲怎麼回事呢系統知道您想要顯示的按鈕大小...?

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    Float32 _spaceBetweenButtons = 8.f; 
    Float32 _offsetY = 32.f; 
    Float32 _buttonWidth = 300.f; // width fo button 
    Float32 _buttonHeight = 32.f; // height of the button 

    for (int i = 0 ; i < 9 ; i++) { 
     UIButton *_myButton = [[UIButton alloc] initWithFrame:CGRectMake(0.f, 0.f, _buttonWidth, _buttonHeight)]; 
     [_myButton setBackgroundColor:[UIColor blackColor]]; 
     [_myButton setTitle:[NSString stringWithFormat:@"button #%d", i] forState:UIControlStateNormal]; // just add some text as title 
     [self.view addSubview:_myButton]; 
     [_mybutton setCenter:CGPointMake(self.view.frame.size.width/2.f, _offsetY + i * (myButton.frame.size.height + _spaceBetweenButtons))]; 
    } 
} 

如果要計算動態按鈕的大小

,並要對齊按鈕的高度視圖的高度,這裏會是一個方法:

NSInteger _numberOfButtons = 20; 
Float32 _spaceBetweenButtons = 8.f; 
Float32 _calculatedHeight = (self.view.frame.size.height - (_numberOfButtons + 1 * _spaceBetweenButtons))/_numberOfButtons; 

和方法與上述方法相同,但我不確定在數百個按鈕的情況下,您將獲得良好的用戶界面。 :)

相關問題