动态创建UIButtons - 逻辑错误

时间:2012-04-06 10:11:55

标签: iphone objective-c

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

取决于我需要初始化UIBUttons的NSMutableArray的计数,然后将String存储的init的值设置为按钮标题。

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

现在我需要创建按钮(numberOfButtonsToBeInitialize返回的数字)

我该怎么做?

3 个答案:

答案 0 :(得分: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)];}

答案 1 :(得分: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];
}

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

答案 2 :(得分: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];
}

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