2012-04-06 76 views
0

我有一個NSMutableArray,我已經在其中保存了一些字符串值。 NSMutableArray的大小可能在2-5之間變化(意思是它可能有2 -5個字符串值存儲在其中)。動態創建UIButton - 邏輯錯誤

取決於NSMutableArray的數量,我需要初始化UIBUttons,然後將String存儲的init的值設置爲按鈕標題。

int numberOfButtonsToBeInitialize= [mutableArr count];// we are finding the number of buttons to be initialize and we assign it to a variable. 

現在我需要創建按鈕(什麼都數由numberOfButtonsToBeInitialize返回)

我怎樣才能做到這一點?

回答

1
for(int i=0;i<numberOfButtonsToBeInitialize;i++){ 
    //init the button 
    UIButton *bout = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     //set the title 
     [bout setTitle:[mutableArr objectAtIndex:i] forState:UIControlStateNormal]; 
     [bout addTarget:self action:@selector(event:) forControlEvents: UIControlEventTouchUpInside]; 
     [self.view addSubview:bout ]; 
     //then you can set the position of your button 
     [bout setFrame:CGRectMake(70,3, 40,40)];} 
0

試試這個:

NSMutableArray *myButtonsArray = [[NSMutableArray alloc] initWithCapacity:0]; 
UIButton *tmpButton; 
for (NSString *bTitle in mutableArr) 
{ 
    tmpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [tmpButton setTitle:bTitle forState:UIControlStateNormal]; 
    // Any additional setup goes here 
    [myButtonsArray addObject:tmpButton]; 
} 

現在你有所有按鈕的數組。你可以迭代這個數組,並在主視圖中添加任何按鈕作爲子視圖。

0

您需要一個for循環。例如:

float buttonWidth=50; 
float margin=5; 
for (int index=0; index<numberOfButtonsToBeInitialize;index++) 
{ 
    UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    NSString* buttonTitle=[mutablearr objectAtIndex:index]; 
    [button setTitle:buttonTitle forState:UIControlStateNormal]; 
    [button setFrame:CGRectMake(0+(buttonWidth+margin)*index, 0, buttonWidth, 30)]; 
    [button setTag:100+index]; 
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:button]; 
} 

在這種情況下,我們在一排(水平)佈局按鈕。根據自己的喜好調整