2012-04-06 78 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]; 
} 

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