IBAction & Buttons programmatically

David West picture David West · Jan 31, 2013 · Viewed 11.9k times · Source

I'm creating buttons programmatically and I then want to add functionality whereby when they are tapped on/pressed, they stay highlighted unless tapped on again. What I'm doing now is creating the buttons and then trying to add an IBAction. However, the issue is I have my button creation in a method and then I'm not sure how to reference the button in my IBAction. Here's my code:

UIButton* testButn = [UIButton buttonWithType:UIButtonTypeCustom];
  [testButn setFrame:CGRectMake(0, 135, 40, 38)];
  [testButn setImage:[UIImage imageNamed:@"test_butn_un.png"] forState:UIControlStateNormal];
  [testButn setImage:[UIImage imageNamed:@"test_butn_pressed.png"]   forState:UIControlStateHighlighted];
[testButn addTarget:self action:@selector(staypressed:) forControlEvents:UIControlEventTouchUpInside];
[self.contentview addSubview:testButn

-(IBAction)staypressed:(id)sender{

//Not sure what to do here, since this method doesn't recognize testButn, How do I reference testButn

Answer

rdelmar picture rdelmar · Jan 31, 2013

The sender is testButn. You should change stayPressed's argument type from (id) to (UIButton *)

Unless an action method is connected to several different classes of objects, it's best to replace the id with whatever object class you're using. This can be useful if you're hooking things up in IB, since it won't let you hook it to the wrong kind of object.

The fact that it's not working isn't because it doesn't recognize your button. Your approach is wrong. I think you need to have an action connected to touch down, and maybe set the selected state to YES. In your button definition, you need to set an imageForState: for the selected state. The way you're doing it now, that method isn't called until touch up.

Something like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton* testButn = [UIButton buttonWithType:UIButtonTypeCustom];
    [testButn setFrame:CGRectMake(0, 135, 40, 38)];
    [testButn setImage:[UIImage imageNamed:@"New_PICT0019.jpg"] forState:UIControlStateNormal];
    [testButn setImage:[UIImage imageNamed:@"New_PICT0002.jpg"]   forState:UIControlStateSelected];
    [testButn addTarget:self action:@selector(stayPressed:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:testButn];
}

-(void)stayPressed:(UIButton *) sender {
    if (sender.selected == YES) {
        sender.selected = NO;
    }else{
        sender.selected = YES;
    }
}