views:

174

answers:

3

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.navigationController.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!

A: 

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

Chuck
A: 
- (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.

Shaggy Frog
Awesome, thanks! I added the code from Mads Mobaek to this as well and it works just fine :o)
StealthRT
+1  A: 

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)

Mads Mobæk
Awesome, thanks!
StealthRT
This is a repeat of what I wrote...
Shaggy Frog
@Shaggy Frog: Guess we wrote it at the same time, happens sometimes
Mads Mobæk