我在循环中创建UIButtons
,如下所示。
for(int i = 1; i <= count; i++){
if(i ==1){
UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, 40, 40)];
[btn1 setImage:image2 forState:UIControlStateNormal];
[self addSubview:btn1];
continue;
}
x = x + 40;
y = y + 50;
UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(x , y, 40, 40)];
[btn2 setImage:image1 forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn2];
}
我将UIButton
点击的事件处理为
-(void) buttonPressed{
}
我需要有关在事件处理方法中单击了哪个按钮的信息。我需要找到点击按钮的框架。如何更改此代码以获取有关发件人的信息。
答案 0 :(得分:4)
在按钮创建时将标记添加到按钮btn.tag=i;
,然后重新定义您的方法
-(void) buttonPressed:(id)sender{
// compare sender.tag to find the sender here
}
答案 1 :(得分:1)
您应该在代码中添加以下几行:
for(int i = 1; i <= count; i++)
{
if(i ==1){
UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, 40, 40)];
[btn1 setImage:image2 forState:UIControlStateNormal];
[btn1 setTag:i]; // This will set tag as the value of your integer i;
[self addSubview:btn1];
continue;
}
x = x + 40;
y = y + 50;
UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(x , y, 40, 40)];
[btn2 setImage:image1 forState:UIControlStateNormal];
[btn2 setTag:i]; // also set tag here.
[btn2 addTarget:self action:@selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn2];
}
现在改变你的IBAction:
-(void) buttonPressed: (id)sender
{
if(sender.tag==1) // determine which button was tapped using this tag property.
{
// Do your action..
}
}
或者你可以这样做。这样你就可以将发件人中的对象复制到这个UIBtton
对象。
-(void) buttonPressed: (id)sender
{
UIButton *tempBtn=(UIButton *) sender;
if(tempBtn.tag==1) // determine which button was tapped using this tag property.
{
// Do your action like..
tempBtn.backgroundColor=[UIColor blueColor];
tempBtn.alpha=0.5;
}
}
因此,在此参数sender
中,它将保留您与之交互的UIButton
,并且您可以访问其属性,如标记,文本等。希望它有帮助..