开发者

Help with iphone button pressed

I am trying to see which button was clicked on so I can preform the correct logic.

This is the code for the buttons:

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.navigati开发者_Go百科onController.view addSubview:button];
[self.navigationController.view addSubview:button2];

And this is how I call the buttonPressedAction:

- (void)buttonPressedAction:(id)sender
{
 UIButton* button = (UIButton*)sender;

if(button.tag == 1)
{
     NSLog(@"1");
}else 
{
     NSLog(@"2");
}
}

But when I use NSLog to see what the sender value is, it crashes.

Any advice for what's happening and how to correct it?

Now corrected :o) THANKS!


As other have pointed out, UIButton does not have a value property. I guess you are trying to detect which button was clicked. Here are two ways to do this:

  1. Use the tag property one each button. I.e. button1.tag = 1, button2.tag = 2. You can then test which button was clicked with if(sender.tag == 1) etc. You could introduce constants for the numbers to make the code more readable.

  2. If you keep a reference to the button, you can check if the reference is equal. Example: if(sender == self.button1)


Probably the best approach would be to give buttons that do different things different actions, but failing that, you could distinguish them by tag.


- (void)buttonPressedAction:(id)sender
{
    UIButton* button = (UIButton*)sender;
    // do something
}

If you were saving the pointers to the button objects you are creating, you could compare the pointers. Or you can just set the tag property for the button, and use that to switch behaviour.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜