如何在循环中创建按钮并为每个按钮分配特定标记

时间:2011-07-02 12:07:39

标签: iphone objective-c ipad

我想创建一个按钮集群。为此我正在使用这样的循环。

for (int i =0; i< [plistArray count];i++) {

    editButton = [[UIButton alloc]initWithFrame:CGRectMake(width-10, -3.6, 39, 35)];
    [editButton setImage:[UIImage imageNamed:@"DeleteButton.png"] forState:UIControlStateNormal];
    [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
}

但当我点击任何随机按钮时,不会调用分配功能。当我点击第一个按钮时(在序列1,2,3中),它会被调用。

1 个答案:

答案 0 :(得分:2)

这是一个:

    #define ButtonHeight 40

    #define OffsetBetweenButtons 20

    #define ButtonHeightPlusOffsetBetweenButtons (ButtonHeight+OffsetBetweenButtons)

//create 6 buttons from 0,1,2,3,4,5 so totally 6 buttons
for(int buttonIndex=0;buttonIndex<=5;buttonIndex++){

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    [button addTarget:self 
               action:@selector(aMethod:)
     forControlEvents:UIControlEventTouchUpInside];

    [button setTitle:@"Button" forState:UIControlStateNormal];

    [button setImage:[UIImage imageNamed:@"DeleteButton.png"] forState:UIControlStateNormal];

    //Set offset in Y axis
    button.frame = CGRectMake(20.0, ButtonHeightPlusOffsetBetweenButtons * buttonIndex , 280.0, 40.0);

    //Set Tag for future identification
    [button setTag:buttonIndex];

    [YourView addSubview:button];

}