2013-02-19 40 views
-2

我有3個不同的按鈕,我用for循環來顯示它在我的UIView。問題是,只有一個按鈕顯示。與不同的UIButton名稱垂直顯示的多個UIButton

float yButton = 50.0; 

for (int i = 0; i < 2; i++) { 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    button.frame = CGRectMake(80.0, yButton + 70.0, 160.0, 40.0); 
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown]; 
    [self.view addSubview:button]; 
    [button setTag:i]; 
} 

此外,如何將按鈕標題設置爲A,B和C(因爲只有3個按鈕)。

回答

3

你給所有按鈕的相同的幀。您需要增加y原點。

在循環的結束,這樣做:

yButton += 50; // pick a value that meets your needs. 

要設置標題,創建具有三個冠軍的數組:

NSArray *titles = @[ @"A", @"B", @"C" ]; 

然後在循環:

[button setTitle:titles[i] forState:UIControlStateNormal]; 
+0

是這樣做,但它不起作用。 – Jahm 2013-02-19 01:39:32

+0

@Jahm用你的實際代碼更新你的問題。另請參閱我的更新以設置標題。 – rmaddy 2013-02-19 01:41:24

+0

謝謝!有些東西缺少;)順便說一下,NSArray應該在for循環中? – Jahm 2013-02-19 01:44:28

2

你給所有按鈕相同的幀:

telcoButton.frame = CGRectMake(80.0, yButton + 70.0, 160.0, 40.0); 

你可能想這樣做:

telcoButton.frame = CGRectMake(80.0, (yButton * i) + 70.0, 160.0, 40.0); 
+0

實際上,假設當前代碼對於第一個按鈕是正確的,你會希望'yButton *(i + 1)+ 70.0'。 – rmaddy 2013-02-19 01:42:57