0

我有一个NSMutableArray,并且我在其中保存了一些字符串值。的大小NSMutableArray可以在 2-5 之间变化(这意味着它可能存储了 2 -5 个字符串值)。

根据NSMutableArray我需要初始化 UIBUttons 的数量,然后将存储在 init 的字符串的值设置为按钮标题。

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

现在我需要创建按钮(无论返回的数字是多少 numberOfButtonsToBeInitialize

我怎样才能做到这一点 ?

4

3 回答 3

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)];}
于 2012-04-06T10:18:25.497 回答
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];
}

现在你有了一个包含所有按钮的数组。您可以迭代此数组并将任何按钮添加为主视图中的子视图。

于 2012-04-06T10:20:39.383 回答
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];
}

在这种情况下,我们将按钮排成一行(水平)。根据自己的喜好进行调整

于 2012-04-06T10:21:48.860 回答