user1315906
user1315906

Reputation: 3494

Creating UIButtons dynamically - Logic Error

I have a NSMutableArray, and i have saving some string values in it. The size of the NSMutableArray could vary from 2-5 (Meaning it might have 2 -5 string values stored in it).

Depending on the count of the NSMutableArray i need to initialize UIBUttons and then set the value of the String stored init to the buttons title.

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

Now i need to create buttons (what ever the number returned by numberOfButtonsToBeInitialize)

How can i do this ?

Upvotes: 0

Views: 225

Answers (3)

touti
touti

Reputation: 1164

  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)];}

Upvotes: 1

Michał Zygar
Michał Zygar

Reputation: 4092

You need a for loop. For example:

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];
}

In this case we layout buttons in a row(horizontally). Adjust to your own preferences

Upvotes: 0

Alladinian
Alladinian

Reputation: 35616

Try this:

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];
}

Now you have an array with all the buttons. You can just iterate this array and add any button as a subview in your main view.

Upvotes: 0

Related Questions