0

我在一个视图上有 42 个自定义按钮。我怎样才能通过按其中任何一个来编辑我想要的已创建按钮。

int a=0; int b=1;

int otstup=10;

for (int i=1; i<=42; i++) {
    CGRect frameBtn = CGRectMake(a+60+otstup, b+otstup, 45, 45);
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:frameBtn];
    [button setBackgroundImage:[UIImage imageNamed:@"EmptyCoin.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
    [button setTag:i];

    [self.view addSubview:button];
    a=a+50;
    if (i%7 == 0)
    {
        a=0;
        b=b+45;
    }
}
4

1 回答 1

2
-(void)pressBtn:(id)sender{ 
UIButton *btn = (UIButton*)sender;
if (btn.tag == 1){
 1st button tapped

} 
else if(btn.tag == 2)
{
 2nd button tapped
}  
}

通过使用上面的代码,您可以区分不同的按钮

更新

您必须创建一个可变数组来存储该数组中的所有按钮。pressBtn您可以在方法中访问该数组

int a=0; int b=1;

int otstup=10;

 for (int i=1; i<=42; i++) {
CGRect frameBtn = CGRectMake(a+60+otstup, b+otstup, 45, 45);
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:frameBtn];
[button setBackgroundImage:[UIImage imageNamed:@"EmptyCoin.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:i];
[buttonAry addObject:button];

[self.view addSubview:button];
a=a+50;
if (i%7 == 0)
{
    a=0;
    b=b+45;
}
}

按钮动作方法

-(void)pressBtn:(id)sender{ 
UIButton *btn = (UIButton*)sender;
if (btn.tag == 7){

UIButton *editButton = [buttonAry objectAtIndex:btn.tag+1];
[editButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
} 

}
于 2013-03-06T12:23:24.420 回答