我正在尝试查看单击了哪个按钮,因此我可以预先形成正确的逻辑。
这是按钮的代码:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(270, 423, 60, 60)];
[button addTarget:self action:@selector(buttonPressedAction:)
forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:[[UIImage imageNamed:@"refreshicon.png"]
stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0]
forState:UIControlStateNormal];
button.tag = 1;
UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 423, 60, 60)];
[button2 addTarget:self action:@selector(buttonPressedAction:)
forControlEvents:UIControlEventTouchUpInside];
[button2 setBackgroundImage:[[UIImage imageNamed:@"login.png"]
stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0]
forState:UIControlStateNormal];
button2.tag = 2;
[self.navigationController.view addSubview:button];
[self.navigationController.view addSubview:button2];
这就是我调用buttonPressedAction
:
- (void)buttonPressedAction:(id)sender
{
UIButton* button = (UIButton*)sender;
if(button.tag == 1)
{
NSLog(@"1");
}else
{
NSLog(@"2");
}
}
但是,当我使用NSLog
来查看发件人值是什么时,它会崩溃。
对正在发生的事情及如何纠正的建议?
现已更正:o)感谢!
答案 0 :(得分:2)
正如其他人所指出的那样,UIButton没有值属性。我想你正试图检测点击了哪个按钮。以下是两种方法:
每个按钮使用tag
属性一个。即button1.tag = 1,button2.tag = 2.然后,您可以测试用if(sender.tag == 1)
等单击了哪个按钮。您可以为数字引入常量,以使代码更具可读性。
如果您保留对按钮的引用,则可以检查引用是否相等。示例:if(sender == self.button1)
答案 1 :(得分:0)
可能最好的方法是给按钮执行不同的操作,但如果不这样做,您可以通过标记区分它们。
答案 2 :(得分:0)
- (void)buttonPressedAction:(id)sender
{
UIButton* button = (UIButton*)sender;
// do something
}
如果要保存指向要创建的按钮对象的指针,则可以比较指针。或者您可以为按钮设置tag
属性,并使用它来切换行为。